:Serialization::SerializationException类型的异常。串行化之前的
程序输出如插3所示:
插3:串行化之前例4的输出
emp1 == emp2 is False
emp2 == emp3 is True
emp1 == emp3 is False
list[0] == list is True
list[0] == emp1 is True
list == emp1 is True
我们对四个目标进行了串行化,前两个代表了不同的Employee对象,而第三个是对第二个的引用,第四个为包含两个元素的数组,这两个元素均引用第一个Employee对象。
程序的输出表明了它们之间的这些关系,反串行化之后的输出见插4:
插4:反串行化之后例4的输出
emp1 == emp2 is False
emp2 == emp3 is False
emp1 == emp3 is False
list[0] == list is True
list[0] == emp1 is False
list == emp1 is False
注意,现在第三个Employee句柄已不再是一个指向第二个Employee对象的句柄了,类似地,尽管list[0]与list都引用同一个Empolyee对象,但对象已不是我们取回的第一个对象了。
在此应看到,当多个对象逐个串行化之后,它们是相关联的,而当反串行化之后,它们的关系并没有因此而恢复,但是,对象内部的关系仍然被维持。
自定义的串行化
默认情况下,当一个对象被串行化时,所有的非静态实例字段都会被写入,并在反串行化期间顺序读回;然而,对包含静态字段的类,这可能会导致一个
问题。
在例5中使用了Point类,其不但包含了用于追踪每个Point x与y坐标的实例变量,而且还会跟踪在程序执行期间创建的Point数目。例如,在例5中,通过显示构造函数调用,创建了4个Point,并将它们串行化到磁盘;当它们被反串行化时,又创建了4个新的Point,因此Point总数现在为8,插5中是
程序的输出:
例5:
using namespace System;
using namespace System::IO;
using namespace System::Runtime::Serialization::Formatters::Binary;
int main()
{
Console::WriteLine("PointCount: {0}", Point::PointCount);
Point^ p1 = gcnew Point(15, 10);
Point^ p2 = gcnew Point(-2, 12);
array<Point^>^ p3 = {gcnew Point(18, -5), gcnew Point(25, 19)};
Console::WriteLine("PointCount: {0}", Point::PointCount);
BinaryFormatter^ formatter = gcnew BinaryFormatter;
Stream^ file = File::Open("Point.ser", FileMode::Create);
formatter->Serialize(file, p1);
formatter->Serialize(file, p2);
formatter->Serialize(file, p3);
file->Close();
file = File::Open("Point.ser", FileMode::Open);
Point^ p4 = static_cast<Point^>(formatter->Deserialize(file));
Console::WriteLine("PointCount: {0}", Point::PointCount);
Point^ p5 = static_cast<Point^>(formatter->Deserialize(file));
Console::WriteLine("PointCount: {0}", Point::PointCount);
array<Point^>^ p6 = static_cast<array<Point^>^>(formatter->Deserialize(file));
Console::WriteLine("PointCount: {0}", Point::PointCount);
file->Close();
Console::WriteLine("p1: {0}, p4: {1}", p1, p4);
Console::WriteLine("p2: {0}, p5: {1}", p2, p5);
Console::WriteLine("p3[0]: {0}, p6[0]: {1}", p3[0], p6[0]);
Console::WriteLine("p3: {0}, p6: {1}", p3, p6);
}
插5:反串行化创建了4个新的Point
PointCount: 0
PointCount: 4
PointCount: 5
PointCount: 6
PointCount: 8
p1: (15,10), p4: (15,10)
p2: (-2,12), p5: (-2,12)
p3[0]: (18,-5), p6[0]: (18,-5)
p3: (25,19), p6: (25,