当BinaryFormatter
将流反序列化为对象时,它似乎在不调用构造函数的情况下创建新对象。BinaryFormatter.Deserialize如何创建新对象?
这是怎么回事?为什么? .NET中是否还有其他功能呢?
这里有一个演示:
[Serializable]
public class Car
{
public static int constructionCount = 0;
public Car()
{
constructionCount++;
}
}
public class Test
{
public static void Main(string[] args)
{
// Construct a car
Car car1 = new Car();
// Serialize and then deserialize to create a second, identical car
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, car1);
stream.Seek(0, SeekOrigin.Begin);
Car car2 = (Car)formatter.Deserialize(stream);
// Wait, what happened?
Console.WriteLine("Cars constructed: " + Car.constructionCount);
if (car2 != null && car2 != car1)
{
Console.WriteLine("But there are actually two.");
}
}
}
输出:
Cars constructed: 1
But there are actually two.
好问题。要解决这个问题,您需要在反序列化过程中做一些指针/参考修正,这可能很难甚至不可能。请注意,“新车”只被调用一次。你可能想在2个过程中尝试这个。 – leppie 2010-08-17 08:03:52
可能重复的[DataContractSerializer不会调用我的构造函数??](http://stackoverflow.com/questions/1076730/datacontractserializer-doesnt-call-my-constructor) – 2010-08-17 08:05:14
注意:我链接到的另一个问题是关于DataContractSerializer ,但BinaryFormatter – 2010-08-17 08:06:53