Customize C# Serialization Guide
In C#, you can customize the way objects are serialized by implementing the ISerializable interface. This interface requires implementing the GetObjectData method and a constructor, which allows you to manually control the serialization and deserialization process of the object.
Here is a simple example demonstrating how to customize the serialization of a Student class.
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}");
}
}
In the example above, we customized the serialization and deserialization methods of the Student class by implementing the ISerializable interface. We used the BinaryFormatter to serialize and deserialize objects. In the custom serialization method, we used the SerializationInfo object to add the property values that need to be serialized, and in the custom deserialization method, we used SerializationInfo to retrieve the deserialized property values.