实例解析C++/CLI的串行化
例4:
using namespace System; using namespace System::IO; using namespace System::Runtime::Serialization::Formatters::Binary; /*1*/ [Serializable] ref class Employee { /* ... */}; int main() { Employee^ emp1 = gcnew Employee(); Employee^ emp2 = gcnew Employee(); Employee^ emp3 = emp2; /*2a*/ Console::WriteLine("emp1 == emp2 is {0}", (emp1 == emp2)); /*2b*/ Console::WriteLine("emp2 == emp3 is {0}", (emp2 == emp3)); /*2c*/ Console::WriteLine("emp1 == emp3 is {0}", (emp1 == emp3)); array<Object^>^ list = gcnew array<Object^>(2); list[0] = emp1; list[1] = list[0]; /*2d*/ Console::WriteLine("list[0] == list[1] is {0}", (list[0] == list[1])); /*2e*/ Console::WriteLine("list[0] == emp1 is {0}", (list[0] == emp1)); /*2f*/ Console::WriteLine("list[1] == emp1 is {0}", (list[1] == emp1)); //将数据串行化到文件 BinaryFormatter^ formatter = gcnew BinaryFormatter; Stream^ file = File::Open("Sr03.ser", FileMode::Create); /*3a*/ formatter->Serialize(file, emp1); /*3b*/ formatter->Serialize(file, emp2); /*3c*/ formatter->Serialize(file, emp3); /*3d*/ formatter->Serialize(file, list); file->Close(); //从文件中反串行化数据--即读取数据 file = File::Open("Sr03.ser", FileMode::Open); /*4a*/ emp1 = static_cast<Employee^>(formatter->Deserialize(file)); /*4b*/ emp2 = static_cast<Employee^>(formatter->Deserialize(file)); /*4c*/ emp3 = static_cast<Employee^>(formatter->Deserialize(file)); /*4d*/ list = static_cast<array<Object^>^>(formatter->Deserialize(file)); file->Close(); /*5a*/ Console::WriteLine("emp1 == emp2 is {0}", (emp1 == emp2)); /*5b*/ Console::WriteLine("emp2 == emp3 is {0}", (emp2 == emp3)); /*5c*/ Console::WriteLine("emp1 == emp3 is {0}", (emp1 == emp3)); /*5d*/ Console::WriteLine("list[0] == list[1] is {0}", (list[0] == list[1])); /*5e*/ Console::WriteLine("list[0] == emp1 is {0}", (list[0] == emp1)); /*5f*/ Console::WriteLine("list[1] == emp1 is {0}", (list[1] == emp1)); } |
在本例中,我们想对Employee类型(在标记1中的用户自定义类型)的对象进行串行化,必须把Serializable属性附加到这个类型上。如果我们试图串行化一个没有标明此属性的类对象,将会抛出一个System::Runtime::Serialization::SerializationException类型的异常。串行化之前的程序输出如插3所示:
插3:串行化之前例4的输出
emp1 == emp2 is False emp2 == emp3 is True emp1 == emp3 is False list[0] == list[1] is True list[0] == emp1 is True list[1] == emp1 is True |
我们对四个目标进行了串行化,前两个代表了不同的Employee对象,而第三个是对第二个的引用,第四个为包含两个元素的数组,这两个元素均引用第一个Employee对象。程序的输出表明了它们之间的这些关系,反串行化之后的输出见插4:
插4:反串行化之后例4的输出
emp1 == emp2 is False emp2 == emp3 is False emp1 == emp3 is False list[0] == list[1] is True list[0] == emp1 is False list[1] == emp1 is False |
注意,现在第三个Employee句柄已不再是一个指向第二个Employee对象的句柄了,类似地,尽管list[0]与list[1]都引用同一个Empolyee对象,但对象已不是我们取回的第一个对象了。
天极yesky
Tags:
作者:佚名评论内容只代表网友观点,与本站立场无关!
评论摘要(共 0 条,得分 0 分,平均 0 分)
查看完整评论