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項空的。 我不明白。
類有另一個變量,我沒有在示例代碼中顯示,我需要自定義序列化爲他們的行爲,所以我需要實現ISerializable。 – 2012-04-03 09:57:01
哪個類,MyList或SomeData?它似乎工作,如果只有其中一個實現ISerializable ... – 2012-04-03 09:58:16
他們都需要實現ISerializable。 – 2012-04-03 10:03:24