首頁  >  文章  >  後端開發  >  什麼是C#中的二進位序列化和反序列化以及如何在C#中實現二進位序列化?

什麼是C#中的二進位序列化和反序列化以及如何在C#中實現二進位序列化?

PHPz
PHPz轉載
2023-09-05 15:53:021334瀏覽

什麼是C#中的二進位序列化和反序列化以及如何在C#中實現二進位序列化?

將一個物件轉換為不可讀的二進位格式稱為二進位序列化。

將二進位格式轉換回可讀的格式稱為反序列化?

要在C#中實現二進位序列化,我們必須使用函式庫System.Runtime.Serialization.Formatters.Binary Assembly。

建立BinaryFormatter類別的對象,並在類別內部使用serialize方法。

範例

Serialize an Object to Binary
[Serializable]
public class Demo {
   public string ApplicationName { get; set; } = "Binary Serialize";
   public int ApplicationId { get; set; } = 1001;
}
class Program {
   static void Main()    {
      Demo sample = new Demo();
      FileStream fileStream = new FileStream(@"C:\Temp\Questions.dat", FileMode.Create);
      BinaryFormatter formatter = new BinaryFormatter();
      formatter.Serialize(fileStream, sample);
      Console.ReadKey();
   }
}

輸出

ÿÿÿÿ

AConsoleApp,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null ConsoleApp.Demok__BackingField-k__BackingField 二進位序列化

範例

Converting back from Binary to Object
[Serializable]
public class Demo {
   public string ApplicationName { get; set; }
   public int ApplicationId { get; set; }
}
class Program {
   static void Main()    {
      FileStream fileStream = new FileStream(@"C:\Temp\Questions.dat ", FileMode.Open);
      BinaryFormatter formatter = new BinaryFormatter();
      Demo deserializedSampledemo = (Demo)formatter.Deserialize(fileStream);
      Console.WriteLine($"ApplicationName { deserializedSampledemo.ApplicationName} --- ApplicationId       { deserializedSampledemo.ApplicationId}");
      Console.ReadKey();
   }
}

輸出

ApplicationName Binary Serialize --- ApplicationId 1001

以上是什麼是C#中的二進位序列化和反序列化以及如何在C#中實現二進位序列化?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除
上一篇:C# 中的集合下一篇:C# 中的集合