2012-04-03 60 views
2

我從BindingList和ISerializable接口派生了類。我想(二進制)序列化這個類,但我不能序列化它的項目。從BindingList和ISerializable接口序列化派生類

示例代碼:

[Serializable] 
    sealed class SomeData : ISerializable 
    { 
     private string name; 

     public SomeData(string name) 
     { 
      this.name = name; 
     } 

     private SomeData(SerializationInfo info, StreamingContext ctxt) 
     { 
      name = info.GetString("Name"); 
     } 

     public void GetObjectData(SerializationInfo info, StreamingContext context) 
     { 
      info.AddValue("Name", name); 
     } 
    } 

    [Serializable] 
    class MyList : BindingList<SomeData>, ISerializable 
    { 
     public MyList() 
     { 
     } 

     private MyList(SerializationInfo info, StreamingContext ctxt) 
     { 
      ((List<SomeData>)this.Items).AddRange((List<SomeData>)info.GetValue("Items", typeof(List<SomeData>))); 
     } 

     public void GetObjectData(SerializationInfo info, StreamingContext context) 
     { 
      info.AddValue("Items", (List<SomeData>)this.Items); 
     } 
    } 

現在,當我試圖序列化。例如像這樣:

 MyList testList = new MyList(); 
     testList.Add(new SomeData("first")); 
     testList.Add(new SomeData("second")); 
     testList.Add(new SomeData("third")); 

     MemoryStream stream = new MemoryStream(); 
     BinaryFormatter formatter = new BinaryFormatter(); 

     formatter.Serialize(stream, testList); 
     stream.Seek(0, SeekOrigin.Begin); 

     MyList deTestList = (MyList)formatter.Deserialize(stream); 

deTestList包含3項空值。

編輯:

有人發現了它的工作原理與此MYLIST構造:

 private MyList(SerializationInfo info, StreamingContext ctxt) 
      : base((List<SomeData>)info.GetValue("Items", typeof(List<SomeData>))) 
     { 
     } 

現在deTestList cointains正確的數據。

但當我嘗試這個辦法:

 private MyList(SerializationInfo info, StreamingContext ctxt) 
      : base((List<SomeData>)info.GetValue("Items", typeof(List<SomeData>))) 
     { 
      ((List<SomeData>)this.Items).AddRange((List<SomeData>)info.GetValue("Items", typeof(List<SomeData>))); 
     } 

deTestList包含6項空的。 我不明白。

回答

1

根本不需要執行ISerializable,只需將Serializable屬性放在類上(除非需要自定義序列化行爲)。它工作正常,你這樣做(但我不知道爲什麼它不適用於您當前的代碼...)

+0

類有另一個變量,我沒有在示例代碼中顯示,我需要自定義序列化爲他們的行爲,所以我需要實現ISerializable。 – 2012-04-03 09:57:01

+0

哪個類,MyList或SomeData?它似乎工作,如果只有其中一個實現ISerializable ... – 2012-04-03 09:58:16

+0

他們都需要實現ISerializable。 – 2012-04-03 10:03:24