将一个对象转换为不可读的二进制格式称为二进制序列化。
将二进制格式转换回可读的格式称为反序列化?
要在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.Demo
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中文网其他相关文章!