Binary Serialization of references using BinaryFormatter
Given the following class structure, will Bar serialize/deserialize as expected?
public class Foo { int x; string y; }
[Serializable]
public class Bar {
Foo[] AllFoos;
Foo SelectedFoo;
public Bar(Foo[] allFoos, int selectedFooIndex) {
开发者_JAVA百科 this.AllFoos = allFoos;
this.SelectedFoo = allFoos[selectedFooIndex];
}
}
I'm curious about a couple of things:
1) Does the BinaryFormatter REQUIRE that the Bar class be decorated with the [Serializable] attribute or implement the ISerializable interface?
2) Does the Foo class also need to be decorated with the [Serializable] attribute?
3) If Bar is simply decorated with the [Serializable] attribute, will the field Bar.SelectedFoo maintain its reference into the array correctly? or will I wind up with a copy of that Foo?
1) Does the BinaryFormatter REQUIRE that the Bar class be decorated withthe [Serializable] attribute or implement the ISerializable interface?
Yes, it does, if the BinaryFormatter is to be used to serialize a Bar instance.
2) Does the Foo class also need to be decorated with the [Serializable] attribute?
Yes, unless you create a custom serialization mechanism that does not involve serializing an instance of a Foo object. For example, you could serialize the x and y components separately, and create a new Foo instance from them in your deserialization code. Otherwise, it must have the attribute or interface.
3) If Bar is simply decorated with the [Serializable] attribute, will the field Bar.SelectedFoo maintain its reference into the array correctly? or will I wind up with a copy of that Foo?
If I remember correctly, arrays are not serializable like this. You must provide your own mechanism (through the ISerializable inteface) for writing and reading arrays.
However, in general, if a graph of serializable objects with mutual references to each other is serialized with the BinaryFormatter, then it will recreate the references correctly without duplicating objects. This should include objects that you specify in your custom serialization code as well, so long as you decorate your Foo with Serializable and pass the same object instance to the formatter from both the array and the field.
精彩评论