【发布时间】:2011-03-30 20:23:16
【问题描述】:
当BinaryFormatter 将流反序列化为对象时,它似乎无需调用构造函数即可创建新对象。
它是如何做到的?为什么? .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: 1But there are actually two.
【问题讨论】:
-
好问题。要解决这个问题,您需要在反序列化期间进行一些指针/引用修复,这可能很难甚至是不可能的。请注意,
new Car仅被调用一次。您可能想在 2 个过程中尝试此操作。 -
注意:我链接的另一个问题是关于 DataContractSerializer,但是 BinaryFormatter 的解释是一样的
-
@Thomas:谢谢,回答了。 FormatterServices.GetUninitializedObject() 很奇怪。
标签: c# constructor serialization binary-serialization