如何在C#中实现自定义序列化

   2024-10-01 4960
核心提示:在C#中实现自定义序列化可以通过实现ISerializable接口来实现。该接口定义了两个方法GetObjectData和ISerializable(Serializatio

在C#中实现自定义序列化可以通过实现ISerializable接口来实现。该接口定义了两个方法GetObjectDataISerializable(SerializationInfo info, StreamingContext context)

下面是一个简单的示例代码:

using System;using System.Runtime.Serialization;using System.IO;using System.Runtime.Serialization.Formatters.Binary;[Serializable]public class CustomObject : ISerializable{    public int Id { get; set; }    public string Name { get; set; }    public CustomObject()    {    }    protected CustomObject(SerializationInfo info, StreamingContext context)    {        Id = (int)info.GetValue("Id", typeof(int));        Name = (string)info.GetValue("Name", typeof(string));    }    public void GetObjectData(SerializationInfo info, StreamingContext context)    {        info.AddValue("Id", Id);        info.AddValue("Name", Name);    }}class Program{    static void Main()    {        CustomObject obj = new CustomObject        {            Id = 123,            Name = "Custom Object"        };        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对象中获取反序列化的数据。

Main方法中,我们创建一个CustomObject对象并将其序列化保存到文件中。然后再从文件中读取并反序列化该对象,并输出结果。

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

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