c#自定义序列化怎么实现

   2024-10-13 5170
核心提示:在C#中,可以通过实现ISerializable接口来自定义序列化过程。以下是一个简单的示例代码:using System;using System.IO;using Sy

在C#中,可以通过实现ISerializable接口来自定义序列化过程。以下是一个简单的示例代码:

using System;using System.IO;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary;[Serializable]public class CustomObject : ISerializable{    public int Id { get; set; }    public string Name { get; set; }    public CustomObject() { }    public CustomObject(int id, string name)    {        Id = id;        Name = name;    }    // 实现ISerializable接口的GetObjectData方法    public void GetObjectData(SerializationInfo info, StreamingContext context)    {        info.AddValue("Id", Id);        info.AddValue("Name", Name);    }    // 自定义的反序列化方法    public CustomObject(SerializationInfo info, StreamingContext context)    {        Id = (int)info.GetValue("Id", typeof(int));        Name = (string)info.GetValue("Name", typeof(string));    }}public class Program{    public static void Main()    {        CustomObject obj = new CustomObject(1, "Object1");        // 序列化对象        IFormatter formatter = new BinaryFormatter();        using (Stream stream = new FileStream("data.bin", FileMode.Create, FileAccess.Write, FileShare.None))        {            formatter.Serialize(stream, obj);        }        // 反序列化对象        using (Stream stream = new FileStream("data.bin", FileMode.Open, FileAccess.Read, FileShare.Read))        {            CustomObject deserializedObj = (CustomObject)formatter.Deserialize(stream);            Console.WriteLine($"Id: {deserializedObj.Id}, Name: {deserializedObj.Name}");        }    }}

在上面的示例中,我们创建了一个自定义的CustomObject类,并实现了ISerializable接口。在GetObjectData方法中,我们将需要序列化的数据添加到SerializationInfo对象中。在自定义的反序列化构造函数中,我们获取SerializationInfo对象中的数据来重新构造对象。

通过这种方式,我们可以完全控制对象的序列化和反序列化过程,实现自定义的序列化逻辑。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号