using namespace System; using namespace System::IO; using namespace System::Runtime::Serialization::Formatters::Binary;
int main() { array<int>^ intArray = {10, 20, 30}; array<float,2>^ floatArray = { {1.2F, 2.4F}, {3.5F, 6.8F}, {8.4F, 9.7F} }; DateTime dt = DateTime::Now; Console::WriteLine("dt >{0}<", dt);
/*1*/ BinaryFormatter^ formatter = gcnew BinaryFormatter;
//将数据串行化到一个文件
/*2*/ Stream^ file = File::Open("Sr01.ser", FileMode::Create);
/*3a*/ formatter->Serialize(file, "Hello"); /*3b*/ formatter->Serialize(file, intArray); /*3c*/ formatter->Serialize(file, floatArray); /*3d*/ formatter->Serialize(file, true); /*3e*/ formatter->Serialize(file, dt); /*3f*/ formatter->Serialize(file, 1000); /*3g*/ formatter->Serialize(file, L'X'); /*3h*/ formatter->Serialize(file, 1.23456F);
/*4*/ file->Close();
//从文件中反串行化数据--即读取数据
/*5*/ file = File::Open("Sr01.ser", FileMode::Open);
/*6a*/ String^ s = static_cast<String^>(formatter->Deserialize(file)); Console::WriteLine("String >{0}<", s);
/*6b*/ array<int>^ newIntArray = static_cast<array<int>^>(formatter->Deserialize(file)); Console::WriteLine("newIntArray:"); for (int i = 0; i < newIntArray->Length; ++i) { Console::Write(" {0}", newIntArray[i]); } Console::WriteLine();
/*6c*/ array<float,2>^ newFloatArray = static_cast<array<float,2>^>(formatter->Deserialize(file)); Console::WriteLine("newFloatArray:"); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 2; ++j) { Console::Write(" {0}", newFloatArray[i,j]); } Console::WriteLine(); }
/*6d*/ bool b = static_cast<bool>(formatter->Deserialize(file)); Console::WriteLine("bool >{0}<", b);
/*6e*/ DateTime newDT = static_cast<DateTime>(formatter->Deserialize(file)); Console::WriteLine("newDT >{0}<", newDT);
/*6f*/ int v = static_cast<int>(formatter->Deserialize(file)); Console::WriteLine("int >{0}<", v);
/*6g*/ wchar_t c = static_cast<wchar_t>(formatter->Deserialize(file)); Console::WriteLine("wchar_t >{0}<", c);
/*6h*/ float f = static_cast<float>(formatter->Deserialize(file)); Console::WriteLine("float >{0}<", f);
/*7*/ file->Close(); } |