2011-09-21 73 views
3

我有對象的列表一類是序列化和反序列化:帶繼承的DataContract?

[DataContract] 
public class Manager 
{ 
    [DataMember] 
    public BigBase[] enemies; 
} 

與子類:

[DataContract] 
[KnownType(typeof(Medium))] 
[KnownType(typeof(Small))] 
public class BigBase 
{ 
    [DataMember] 
    public bool isMoving; 
} 
[DataContract] 
public class Medium : BigBase 
{ 
} 
[DataContract] 
public class Small: BigBase 
{ 
} 

現在什麼奇怪的反序列化的敵人數組將包含正確的反序列化BigBase類時但是每個中等和小類沒有isMoving的正確值。

+0

沒有一些樣品**測試代碼**我懷疑有人會想幫你。 – Icarus

回答

2

你需要把KnownType屬性上Manager

[DataContract] 
[KnownType(typeof(Medium))] 
[KnownType(typeof(Small))] 
public class Manager 
{ 
    [DataMember] 
    public BigBase[] enemies; 
} 

因爲它其中有BigBase一個數組,其元素可能是派生類以及經理。因此DataContractSerializer將知道序列化和反序列化Manager對象(並且全部是DataMember)期望從陣列中得到什麼。

0
[DataContract] 
public class Medium : BigBase 
{ 
    [DataMember] 
    public string UpgradedName; 
} 

我沒有看到這個測試代碼。我認爲你的序列化代碼是錯誤的。

樣來電:

Manager test = new Manager(); 

      Medium medium = new Medium() {isMoving = true,Name = "medium", UpgradedName = "mediaum name"}; 
      //some items in array 
      test.enemies = new BigBase[] {medium,new Small{isMoving = false},new Small{isMoving = true}, new BigBase {Name = "bigbase", isMoving = true}, new BigBase {Name = "bigbase2", isMoving = true}, new BigBase {Name = "bigbase3", isMoving = true}} ; 

      DataContractSerializer serializer = new DataContractSerializer(typeof (Manager)); 
      FileStream writer = new FileStream("test123.txt", FileMode.Create); 
      serializer.WriteObject(writer, test); 
      writer.Close(); 
      writer = new FileStream("test123.txt", FileMode.Open); 
      Manager deserializedmanager = serializer.ReadObject(writer) as Manager; 
      //verify serialized object 
      Console.WriteLine("medium object:"+ (deserializedmanager.enemies[0] as Medium).UpgradedName);