Computer >> Máy Tính >  >> Lập trình >> C#

Binary Serialization và Deserialization trong C # là gì và làm thế nào để đạt được Binary Serialization trong C #?

Việc chuyển đổi một đối tượng sang định dạng nhị phân không ở định dạng con người có thể đọc được được gọi là Binary Serialization.

Chuyển đổi lại định dạng nhị phân thành định dạng có thể đọc được của con người được gọi là deserialization?

Để đạt được tuần tự hóa nhị phân trong C #, chúng ta phải sử dụng thư viện System.Runtime.Serialization.Formatters.Binary Hội

Tạo một đối tượng của lớp BinaryFormatter và sử dụng phương thức tuần tự hóa bên trong lớp

Ví dụ

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

Đầu ra

ÿÿÿÿ

AConsoleApp, Phiên bản =1.0.0.0, Văn hóa =trung lập, PublicKeyToken =null ConsoleApp.Demo k__BackingField- k__BackingField Binary Serializeé

Ví dụ

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

Đầu ra

ApplicationName Binary Serialize --- ApplicationId 1001