温馨提示×

c#序列化和反序列化怎么实现

c#
小亿
98
2024-08-01 17:11:13
栏目: 编程语言

在C#中,可以使用System.Runtime.Serialization命名空间中的类来实现对象的序列化和反序列化。具体步骤如下:

  1. 定义一个需要序列化的类,并为其添加[Serializable]属性,表示该类可以被序列化。
[Serializable] public class MyClass { public int Id { get; set; } public string Name { get; set; } } 
  1. 创建一个BinaryFormatter对象,用于序列化和反序列化对象。
using System.Runtime.Serialization.Formatters.Binary; BinaryFormatter formatter = new BinaryFormatter(); 
  1. 序列化对象:
MyClass obj = new MyClass { Id = 1, Name = "John" }; using (FileStream fileStream = new FileStream("data.dat", FileMode.Create)) { formatter.Serialize(fileStream, obj); } 
  1. 反序列化对象:
MyClass newObj; using (FileStream fileStream = new FileStream("data.dat", FileMode.Open)) { newObj = (MyClass)formatter.Deserialize(fileStream); } Console.WriteLine($"Id: {newObj.Id}, Name: {newObj.Name}"); 

上述代码演示了如何将MyClass对象序列化到文件中,然后再从文件中反序列化得到新的对象。你也可以使用其他格式如XML或JSON来序列化对象,只需要相应地更换Formatter类型即可。

0