在C#中,可以通过实现ISerializable接口来自定义对象的序列化方式
在C#中,可以通过实现ISerializable接口来自定义对象的序列化方式。ISerializable接口要求实现GetObjectData方法和一个构造函数,通过这两个方法可以手动控制对象的序列化和反序列化过程。
以下是一个简单的示例,展示如何自定义一个Student类的序列化方式:
usingSystem;
usingSystem.IO;
usingSystem.Runtime.Serialization;
usingSystem.Runtime.Serialization.Formatters.Binary;
[Serializable]
publicclassStudent:ISerializable
{
publicstringName{get;set;}
publicintAge{get;set;}
publicStudent(stringname,intage)
{
this.Name=name;
this.Age=age;
}
//自定义序列化方法
publicvoidGetObjectData(SerializationInfoinfo,StreamingContextcontext)
{
info.AddValue("Name",this.Name);
info.AddValue("Age",this.Age);
}
//自定义反序列化方法
publicStudent(SerializationInfoinfo,StreamingContextcontext)
{
this.Name=(string)info.GetValue("Name",typeof(string));
this.Age=(int)info.GetValue("Age",typeof(int));
}
}
classProgram
{
staticvoidMain()
{
Studentstudent=newStudent("Alice",20);
//序列化对象
IFormatterformatter=newBinaryFormatter();
using(Streamstream=newFileStream("student.bin",FileMode.Create,FileAccess.Write,FileShare.None))
{
formatter.Serialize(stream,student);
}
//反序列化对象
StudentdeserializedStudent;
using(Streamstream=newFileStream("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来获取反序列化的属性值。
版权声明
本文仅代表作者观点,不代表博信信息网立场。