當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