2012-08-01 23 views
4

基本上,当通过线返回类型为YoyoData的对象时,下面的代码是否应该工作并序列化string Yoyo定义接口中的序列化数据成员,然后在实现上述接口的类中使用它

public interface IHelloV1 
    { 
     #region Instance Properties 

     [DataMember(Name = "Yoyo")] 
     string Yoyo { get; set; } 

     #endregion 
    } 


    [DataContract(Name = "YoyoData", Namespace = "http://hello.com/1/IHelloV1")] 
    public class YoyoData : IHelloV1 
    { 
     string Yoyo { get; set; } 

     public YoyoData() 
     { 
      Yoyo = "whatever"; 
     } 
    } 
} 
+0

看起来像一个好奇的混合责任。 – 2012-08-01 22:26:00

+0

@亨克 - 它是从代码继承强加给我的,我只是想知道它是否会工作;-) – Matt 2012-08-01 22:28:20

回答

5

我不认为它会。

DataMember属性不在派生类中继承。

有关更多详细信息,请参阅DataMemberAttribute类型的文档及其定义方式:http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.aspx。 该属性指定属性Inherited = false,意味着该属性不会传播到派生类。

有关属性上的Inherited属性的更多详细信息,请参阅http://msdn.microsoft.com/en-us/library/84c42s56(v=vs.71).aspx

无论如何,这意味着在您的班级定义DataContract,属性Yoyo将不会被视为DataMember因此对我而言,它不会按预期工作。

+0

我的测试证实了这一点。我只是好奇,如果我错过了一步,但你说的话是有道理的。谢谢! – Matt 2012-08-01 22:36:38

3

这样看来,它不工作

using System.Runtime.Serialization; 
using System.IO; 
using System; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main() 
     { 
      IHelloV1 yoyoData = new YoyoData(); 
      var serializer = new DataContractSerializer(typeof(YoyoData)); 

      byte[] bytes; 
      using (var stream = new MemoryStream()) 
      { 
       serializer.WriteObject(stream, yoyoData); 
       stream.Flush(); 
       bytes = stream.ToArray(); 
      } 

      IHelloV1 deserialized; 
      using (var stream = new MemoryStream(bytes)) 
      { 
       deserialized = serializer.ReadObject(stream) as IHelloV1; 
      } 

      if (deserialized != null && deserialized.Yoyo == yoyoData.Yoyo) 
      { 
       Console.WriteLine("It works."); 
      } 
      else 
      { 
       Console.WriteLine("It doesn't work."); 
      } 

      Console.ReadKey(); 
     } 
    } 

    public interface IHelloV1 
    { 
     #region Instance Properties 

     [DataMember(Name = "Yoyo")] 
     string Yoyo { get; set; } 

     #endregion 
    } 


    [DataContract(Name = "YoyoData", Namespace = "http://hello.com/1/IHelloV1")] 
    public class YoyoData : IHelloV1 
    { 
     public string Yoyo { get; set; } 

     public YoyoData() 
     { 
      Yoyo = "whatever"; 
     } 
    } 
} 

但是,如果你扔在类属性,属性而不是界面特性,它的工作。

相关问题