将对象转换为非人类可读格式的二进制格式称为二进制序列化。
将二进制格式转换回人类可读格式称为反序列化?
为了在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,版本= 1.0.0.0,区域性=中性,PublicKeyToken =空ConsoleApp.Demo <ApplicationName> k__BackingField- <ApplicationId> k__BackingField BinarySerializeé
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