How does serialization work without constructors?
I'm not sure how this piece of code works.
[Serializable]
class Blah
{
public Blah(int value)
{
this.value = value;
}
public int value;
}
开发者_StackOverflowBinaryFormatter b = new BinaryFormatter();
Blah blah = new Blah(4);
MemoryStream s = new MemoryStream();
b.Serialize(s, blah);
s.Seek(0, SeekOrigin.Begin);
blah = null;
blah = (Blah)b.Deserialize(s);
As I don't have a parameterless constructor, it seems strange that the deserializer can create a new instance of Blah.
The deserialization process uses FormatterServices.GetUninitializedObject
which gets an object without calling any constructor.
The serializer doesn't call a constructor when it deserializes an object. The values of the fields are set directly. It doesn't need to create the object (via new
) it just creates storage, fills it, and casts it as a Blah
type.
BinaryFormatter
uses voodoo method called FormatterServices.GetUninitializedObject
:
...the object is initialized to zero and no constructors are run
精彩评论