![](/img/trans.png)
[英]DataContractSerializer not Serializing member of class that inherits ISerializable
[英]Serializing derived class from BindingList and ISerializable interface
我從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個null項。
編輯:
有人發現它可以與此MyList構造函數一起使用:
private MyList(SerializationInfo info, StreamingContext ctxt)
: base((List<SomeData>)info.GetValue("Items", typeof(List<SomeData>)))
{
}
現在,deTestList包含正確的數據。
但是當我嘗試這個:
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個null項。 我不明白
您根本不需要實現ISerializable
,只需要在您的類上放置Serializable
屬性(除非您需要自定義序列化行為)。 在您執行此操作時效果很好(但是我不確定為什么它不適用於您當前的代碼...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.