• ADADADADAD

    C#序列化怎么自定义[ 编程知识 ]

    编程知识 时间:2024-11-20 12:04:01

    作者:文/会员上传

    简介:

    在C#中,可以通过实现ISerializable接口来自定义对象的序列化方式。ISerializable接口要求实现GetObjectData方法和一个构造函数,通过这两个方法可以手动控制对象的序列化和反

    以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。

    在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来获取反序列化的属性值。

    C#序列化怎么自定义.docx

    将本文的Word文档下载到电脑

    推荐度:

    下载
    热门标签: c