在C#中,可以使用System.Runtime.Serialization
命名空间中的类来实现对象的序列化和反序列化。具体步骤如下:
[Serializable]
属性,表示该类可以被序列化。[Serializable] public class MyClass { public int Id { get; set; } public string Name { get; set; } }
BinaryFormatter
对象,用于序列化和反序列化对象。using System.Runtime.Serialization.Formatters.Binary; BinaryFormatter formatter = new BinaryFormatter();
MyClass obj = new MyClass { Id = 1, Name = "John" }; using (FileStream fileStream = new FileStream("data.dat", FileMode.Create)) { formatter.Serialize(fileStream, obj); }
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
类型即可。