在C#中,可以通过实现ISerializable接口来自定义对象的序列化方式。ISerializable接口要求实现GetObjectData方法和一个构造函数,通过这两个方法可以手动控制对象的序列化和反序列化过程。
以下是一个简单的示例,展示如何自定义一个Student类的序列化方式:
using System;using System.IO;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary;[Serializable]public class Student : ISerializable{ public string Name { get; set; } public int Age { get; set; } public Student(string name, int age) { this.Name = name; this.Age = age; } // 自定义序列化方法 public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Name", this.Name); info.AddValue("Age", this.Age); } // 自定义反序列化方法 public Student(SerializationInfo info, StreamingContext context) { this.Name = (string)info.GetValue("Name", typeof(string)); this.Age = (int)info.GetValue("Age", typeof(int)); }}class Program{ static void Main() { Student student = new Student("Alice", 20); // 序列化对象 IFormatter formatter = new BinaryFormatter(); using (Stream stream = new FileStream("student.bin", FileMode.Create, FileAccess.Write, FileShare.None)) { formatter.Serialize(stream, student); } // 反序列化对象 Student deserializedStudent; using (Stream stream = new FileStream("student.bin", FileMode.Open, FileAccess.Read, FileShare.Read)) { deserializedStudent = (Student)formatter.Deserialize(stream); } Console.WriteLine($"Name: {deserializedStudent.Name}, Age: {deserializedStudent.Age}"); }}在上面的示例中,通过实现ISerializable接口,我们自定义了Student类的序列化和反序列化方法,并通过BinaryFormatter来进行对象的序列化和反序列化操作。自定义序列化方法中使用SerializationInfo对象来添加需要序列化的属性值,自定义反序列化方法中使用SerializationInfo来获取反序列化的属性值。




