已知类型序列化问题

时间:2010-09-24 05:59:38

标签: .net wcf datacontract

阅读了文档和许多文章后,我认为以下内容应该有效,但事实并非如此。

这就是我的数据交易的结构。

[DataContract]
[KnownType(typeof(Friend))]
public class Person
{
   private string name;

   [DataMember]
   public string Name { get { return name; } set { name = value; }}

   private Place location;

   [DataMember]
   public Place Location { get { return location; } set { location = value; }}
}

[DataContract]
public class Friend : Person
{
   private int mobile;

   [DataMember]
   public int Mobile { get { return mobile; } set { mobile = value; }}
}

[DataContract]
[KnownType(typeof(City))]
public class Place
{
   private int altitude;

   [DataMember]
   public int Altitude { get { return altitude; } set { altitude = value; }}
}

[DataContract]
public class City : Place
{
   private int zipCode;

   [DataMember]
   public int ZipCode { get { return zipCode; } set { zipCode = value; }}
}

客户端发送以下示例对象:

Person tom = new Friend();
tom.Name = "Tom";

Place office = new City();
office.Altitude = 500;
office.ZipCode = 900500;

tom.Location = office;

问题是由于某种原因没有Place值被序列化。

我犯了什么错误?

感谢。

2 个答案:

答案 0 :(得分:0)

DataContract使用选择加入,Serializable使用选择退出。这就是使用Serializable时它的工作原理。 您需要将支持字段标记为DataMembers,而不是属性:

[DataContract]
[KnownType(typeof(Friend))]
public class Person
{
   [DataMember]
   private string name;

   public string Name { get { return name; } set { name = value; }}

   [DataMember]
   private Place location;

   public Place Location { get { return location; } set { location = value; }}
}

[DataContract]
public class Friend : Person
{
   [DataMember]
   private int mobile;

   public int Mobile { get { return mobile; } set { mobile = value; }}
}

[DataContract]
[KnownType(typeof(City))]
public class Place
{
   [DataMember]
   private int altitude;

   public int Altitude { get { return altitude; } set { altitude = value; }}
}

[DataContract]
public class City : Place
{
   [DataMember]   
   private int zipCode;

   public int ZipCode { get { return zipCode; } set { zipCode = value; }}
}

答案 1 :(得分:0)

经过多次挫折后,我的数据采集设计存在缺陷:(