/*3*/ Console::WriteLine("{0}{1} found", word, (dictionary->Contains(word) ? "" : " not"));
}
}
插2:使用反串行化进行字典查找
Dictionary contains 20159 entries
Enter a word: house
house found
Enter a word: houses
houses not found
Enter a word: brick
brick found
Enter a word: manly
manly not found
此处最重要的是,我们能在单个函数调用中,串行、反串行化任意大小、任意复杂性的对象。
处理多个句柄
当我们传递一个对象的句柄给Serialize时,似乎会在底层对对象进行一个复制,那么,实际情况真的是这样吗?假设我们把包含有多个句柄的一个对象写入到其他对象中,或者我们调用Serialize两次,每次都给它同一个对象的句柄呢?我们真的想得到同一对象的多个副本吗?在例4中演示了这个过程:
例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 = list[0];
/*2d*/ Console::WriteLine("list[0] == list is {0}", (list[0] == list));
/*2e*/ Console::WriteLine("list[0] == emp1 is {0}", (list[0] == emp1));
/*2f*/ Console::WriteLine("list == emp1 is {0}", (list == 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 is {0}", (list[0] == list));
/*5e*/ Console::WriteLine("list[0] == emp1 is {0}", (list[0] == emp1));
/*5f*/ Console::WriteLine("list == emp1 is {0}", (list == emp1));
}
在本例中,我们想对Employee类型(在标记1中的用户自定义类型)的对象进行串行化,必须把Serializable属性附加到这个类型上。如果我们试图串行化一个没有标明此属性的类对象,将会抛出一个System::Runtime: