国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

實例解析C++/CLI的串行化

2019-11-17 05:28:01
字體:
供稿:網(wǎng)友

  串行化可使對象被轉(zhuǎn)換為某種外部的形式,比如以文件存儲的形式供程序使用,或通過程序間的通訊發(fā)送到另一個處理過程。轉(zhuǎn)換為外部形式的過程稱為"串行化",而逆過程稱為"反串行化"。

  簡介
  
  請看例1中的示例,其將多個對象類型的值寫入到一個新的磁盤文件中,關(guān)閉文件,接著再把這些值重新讀取到內(nèi)存中。

  例1:

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;

 //將數(shù)據(jù)串行化到一個文件

 /*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();

 //從文件中反串行化數(shù)據(jù)--即讀取數(shù)據(jù)

 /*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();
}
  在標記1中,我們定義了一個BinaryFormatter類型的變量,此種類型的任意對象都可以二進制的形式進行串行與反串行化。

  在標記2中,用指定的名稱創(chuàng)建了一個新的文件,后綴 .ser沒有非凡的意思,這是約定俗成的表示這是一個串行化數(shù)據(jù)文件。從標記3a至3h,表示一個對象被串行化至文件中。在字符串的情況下,每個字符都被寫入;在數(shù)組的情況下,所有元素都被寫入;在日期時間的情況下,類型中包含的所有數(shù)據(jù)及有關(guān)依靠項都被寫入;在為原始類型值的情況下,它們先被裝箱,然后對應的對象被寫入。上述動作中,串行化只需要接收一個Object^類型參數(shù)的對象即可。

  通過調(diào)用Deserialize函數(shù),可取回串行化后的數(shù)據(jù),如標記6a中所示;因為此函數(shù)返回一個Object^類型的值,所以需要把它轉(zhuǎn)換為相應的值。程序的輸出如插1所示:

  插1:例1中串行化、反串行化的輸出


String >Hello<
newIntArray
10 20 30
newFloatArray:
1.2 2.4
3.5 6.8
8.4 9.7
bool >True<
newDT >9/29/2005 3:25:44 PM<
int >1000<
wchar_t >X<
float >1.23456< 串行化包含引用的對象

  在前一個例子中,我們對相關(guān)類型進行了簡單的讀寫。那么,假如一個對象中包含了其他對象的句柄呢?試想有一個超過兩萬字的字典,存儲在一個能通過鍵值索引的集合中,而在標準模板庫中,就提供了一個這樣的集合--哈希表(Hashtable),如例2中所示:

  例2:

using namespace System;
using namespace System::IO;
using namespace System::Collections;
using namespace System::Runtime::Serialization::Formatters::Binary;

int main()
{
 /*1*/ Hashtable^ dictionary = gcnew Hashtable(21000);

 StreamReader^ inStream = File::OpenText("dictionary.txt"); //打開字典文件
 String^ str;

 while ((str = inStream->ReadLine()) != nullptr)
 {
  /*2*/ dictionary->Add(str, nullptr);
 }

 inStream->Close();
 /*3*/ Console::WriteLine("Dictionary contains {0} entries", dictionary->Count);

 BinaryFormatter^ formatter = gcnew BinaryFormatter();
 Stream^ file = File::Open("dictionary.ser", FileMode::Create);
 /*4*/ formatter->Serialize(file, dictionary);
 file->Close();
}
  在標記1中,我們先分配了一個初始化為21000個條目的哈希表(這樣做只是為了加快處理速度,在條目相加時不需要重新進行分配),接著從一個文本文件中,一次一行地讀入字,并將其添加到標記2的哈希表中。請注重,在定義中,哈希表的每個條目都由(鍵/值)對組成。但在我們的程序中,鍵也是值,所以在第二個參數(shù)中使用了nullPRt。

  哈希表中的鍵值必須是唯一的,而添加進來的任何類型的對象都必須重載System::對象名 GetHashCode函數(shù)--字符串也一樣。

  一旦文件中所有的字被讀取并添加到哈希表中,就可通過一個簡單的Serialize調(diào)用,把哈希表寫到磁盤上,如標記4所示。在例3中,我們讀入這個字典,并在其中查找用戶提供的字,插2是對應的輸出。

  例3:

using namespace System;
using namespace System::IO;
using namespace System::Collections;
using namespace System::Runtime::Serialization::Formatters::Binary;

int main()
{
 BinaryFormatter^ formatter = gcnew BinaryFormatter;

 Stream^ file = File::Open("dictionary.ser", FileMode::Open);
 /*1*/ Hashtable^ dictionary = static_cast<Hashtable^>(formatter->Deserialize(file));
 file->Close();

 /*2*/ Console::WriteLine("Dictionary contains {0} entries", dictionary->Count);

 String^ Word;
 while (true)
 {
  Console::Write("Enter a word: ");
  word = Console::ReadLine();
  if (word == nullptr)
  {
   break;
  }
  /*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
  此處最重要的是,我們能在單個函數(shù)調(diào)用中,串行、反串行化任意大小、任意復雜性的對象。 處理多個句柄

  當我們傳遞一個對象的句柄給Serialize時,似乎會在底層對對象進行一個復制,那么,實際情況真的是這樣嗎?假設我們把包含有多個句柄的一個對象寫入到其他對象中,或者我們調(diào)用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[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));

 //將數(shù)據(jù)串行化到文件

 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();

 //從文件中反串行化數(shù)據(jù)--即讀取數(shù)據(jù)

 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對象,而第三個是對第二個的引用,第四個為包含兩個元素的數(shù)組,這兩個元素均引用第一個Employee對象。程序的輸出表明了它們之間的這些關(guān)系,反串行化之后的輸出見插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
  注重,現(xiàn)在第三個Employee句柄已不再是一個指向第二個Employee對象的句柄了,類似地,盡管list[0]與list[1]都引用同一個Empolyee對象,但對象已不是我們?nèi)』氐牡谝粋€對象了。

  在此應看到,當多個對象逐個串行化之后,它們是相關(guān)聯(lián)的,而當反串行化之后,它們的關(guān)系并沒有因此而恢復,但是,對象內(nèi)部的關(guān)系仍然被維持。
自定義的串行化

  默認情況下,當一個對象被串行化時,所有的非靜態(tài)實例字段都會被寫入,并在反串行化期間順序讀回;然而,對包含靜態(tài)字段的類,這可能會導致一個問題。

  在例5中使用了Point類,其不但包含了用于追蹤每個Point x與y坐標的實例變量,而且還會跟蹤在程序執(zhí)行期間創(chuàng)建的Point數(shù)目。例如,在例5中,通過顯示構(gòu)造函數(shù)調(diào)用,創(chuàng)建了4個Point,并將它們串行化到磁盤;當它們被反串行化時,又創(chuàng)建了4個新的Point,因此Point總數(shù)現(xiàn)在為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[1]: {0}, p6[1]: {1}", p3[1], p6[1]);
}
  插5:反串行化創(chuàng)建了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[1]: (25,19), p6[1]: (25,19)
  當調(diào)用Point類的公有構(gòu)造函數(shù)來構(gòu)造一個新對象時,Point計數(shù)字段也會相應增長;而當我們反串行化一個或多個Point時,問題發(fā)生了,對Point的Deserialize調(diào)用實際上創(chuàng)建了一個新的Point對象,但它并沒有為這些對象調(diào)用任何的構(gòu)造函數(shù)啊。另外要明確一點,即使新Point數(shù)被增量1 ,PointCount也不會自動增長。我們可重載由接口ISerializable(從System::Runtime::Serialization)實現(xiàn)的默認的串行與反串行動作;這個接口需要定義一個調(diào)用GetObjectData的函數(shù),這個函數(shù)就可以答應我們重載串行化過程。

  GetObjectData函數(shù)的目的是,以串行化一個父類對象所需的數(shù)據(jù),增加一個SerializationInfo對象,在此,名稱、值、類型信息都被提供給AddValue函數(shù),并由對象作為第二個參數(shù)。名稱字符串可為任意,只要它在這種類型的串行化中唯一就行了。(假如使用了兩個相同的名稱,會拋出SerializationException異常。)

  假如要重載反串行化過程,必須定義另一個構(gòu)造函數(shù),注重這個構(gòu)造為私有類型,因為它只會被反串行化機制所調(diào)用,沒有從外部訪問的必要。

  串行化的格式
  
  以上所有串行化的例子當中,我們使用了BinaryFormatter類型,其以某種能被高效地處理的壓縮格式來存儲數(shù)據(jù);然而,其他格式也能做到這點,例如,可使用一個SOAP,SOAP(Simple Object access Protocol--簡單對象訪問協(xié)議)是一種用于在Web上交換結(jié)構(gòu)化及類型信息的簡單的、基于xml的協(xié)議,該協(xié)議未包含任何應用程序或傳輸語義,所以它具有高度模塊化及擴展性的特點。當然,大家也能創(chuàng)建其他的自定義格式。


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 朝阳市| 岳西县| 丹阳市| 酉阳| 桐乡市| 阿城市| 静宁县| 彭州市| 霞浦县| 永德县| 永善县| 贵德县| 永仁县| 彰武县| 涟水县| 翁牛特旗| 大安市| 临沭县| 图们市| 乌拉特中旗| 灌南县| 武胜县| 定安县| 江都市| 灵璧县| 革吉县| 平潭县| 兰溪市| 蓝山县| 湘阴县| 镇巴县| 合作市| 和静县| 宾阳县| 乐至县| 盘锦市| 金门县| 枞阳县| 大庆市| 无棣县| 长兴县|