什么是 C# 中的二进制序列化和反序列化,如何在 C# 中实现二进制序列化?
将对象转换为二进制格式(非人类可读格式)称为二进制序列化。
将二进制格式转换回人类可读格式称为反序列化?
要在 C# 中实现二进制序列化,我们必须使用库System.Runtime.Serialization.Formatters.Binary 程序集
创建一个 BinaryFormatter 类的对象并在类内部使用序列化方法
示例
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.Demo<ApplicationName>k__BackingField-<ApplicationId>k__BackingField Binary Serializeé
示例
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
广告