当前位置: 首页 > 建站教程

C#序列化怎么自定义

时间:2026-01-28 13:50:39

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


上一篇:php move_uploaded_file函数怎么用
下一篇:python中sys.exit的用法是什么
C
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器
  • 英特尔第五代 Xeon CPU 来了:详细信息和行业反应
  • 由于云计算放缓引发扩张担忧,甲骨文股价暴跌
  • Web开发状况报告详细介绍可组合架构的优点
  • 如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳
  • 美光在数据中心需求增长后给出了强有力的预测
  • 2027服务器市场价值将接近1960亿美元
  • 生成式人工智能的下一步是什么?
  • 分享在外部存储上安装Ubuntu的5种方法技巧
  • 全球数据中心发展的关键考虑因素
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器

    英特尔第五代 Xeon CPU 来了:详细信息和行业反应

    由于云计算放缓引发扩张担忧,甲骨文股价暴跌

    Web开发状况报告详细介绍可组合架构的优点

    如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳

    美光在数据中心需求增长后给出了强有力的预测

    2027服务器市场价值将接近1960亿美元

    生成式人工智能的下一步是什么?

    分享在外部存储上安装Ubuntu的5种方法技巧

    全球数据中心发展的关键考虑因素