2010-09-24 47 views
2

阅读文档和许多文章后,我认为以下内容应该可以工作,但它不会。已知类型序列化问题

这就是我的数据合同的结构。

[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; 

问题对于没有地方值的一些原因被序列化。

我犯了什么错误?

谢谢。

+0

越来越序列化的高度或任何有关的地方呢? ? – Jeff 2010-09-24 06:14:48

+0

当客户提交人时没有将Place的属性序列化 – mob1lejunkie 2010-09-24 06:23:25

+0

夫妻问题:1)您的客户端代码无法编译:office.ZipCode不是有效的赋值。 2)我把你的数据合约粘贴到VS2010中,做了一个返回“Person”的函数,并使用WCF Test容器调用它。有效。所以问题可能在于问题中没有显示的代码。 – ErnieL 2010-09-26 06:27:45

回答

0

后我datacontract的设计是有缺陷:(

+2

小心分享缺陷?有几个人花时间试图了解你的问题。如果您现在找到它,那么分享根本原因会很好。 – ErnieL 2010-09-29 03:03:03

+1

在实际实施中,人员和朋友都参考了位置。客户在Person上设置Location对象的属性,但不在Friend上的Location对象上。这是Location对象的属性未被序列化的原因。 – mob1lejunkie 2010-09-29 23:40:32

0

DataContract使用opt-in,Serializeable使用Opt-out。这就是为什么它在使用Serializeable时的原因。 你需要标记的支持领域的数据成员,而不是性能:太多的无奈原来

[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; }} 
} 
+0

1)我还没有尝试过使用Serializable,我使用DataContractSerializer进行了测试。 – mob1lejunkie 2010-09-27 22:47:43

+0

2)根据文档DataMember属性可以应用于属性,所以我不认为这是问题。 http://msdn.microsoft.com/en-us/library/ms730167(v=VS.85).aspx – mob1lejunkie 2010-09-27 22:48:50