Reputation: 21
I have derived class from BindingList and ISerializable interface. I want to (binary) serialize this class but I am not able to serialize its items.
Sample code:
[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);
}
}
Now when I try to serialize it. For example like this:
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 contains 3 items of null.
Edited:
Somebody found out that it works with this MyList constructor:
private MyList(SerializationInfo info, StreamingContext ctxt)
: base((List<SomeData>)info.GetValue("Items", typeof(List<SomeData>)))
{
}
Now deTestList cointains correct data.
But when I try this:
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 contains 6 items of null. I don't understand it.
Upvotes: 2
Views: 1889
Reputation: 292555
You don't need to implement ISerializable
at all, you just need to put the Serializable
attribute on your class (unless you need to customize the serialization behavior). It works fine in you do that (but I'm not sure why it doesn't work with your current code...)
Upvotes: 1