2010-09-24 70 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