C#序列化

序列化操作

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public class BinarySerializer
{
#region Serialize
    public static void SerializeToFile<T>(T obj, string fileDir, string fullName)
    {
        if(!(Directory.Exists(fileDir)))
        {
            Directory.CreateDirectory(fileDir);
        }

        string fullPath = string.Format(@"{0}\{1}", fileDir, fullName);
        using(FileStream fs = new FileStream(fullPath, FileMode.OpenOrCreate))
        {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(fs, obj);
            fs.Flush();
        }
    }

    public static string SerializeToString<T>(T obj)
    {
        using(MemoryStream ms = new MemoryStream())
        {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, obj);
            return System.Text.Encoding.UTF8.GetString(ms.ToArray());
        }
    }
#endregion

#region Deserialize
    public static T DeserializeFromFile<T>(string path) where T : class
    {
        using(FileStream fs = new FileStream(path, FileMode.Open))
        {
            
            BinaryFormatter bf = new BinaryFormatter();
            return bf.Deserialize(fs) as T;
        }
    }

   public static T DeserializeFromString<T>(string content) where T : class
   {
       byte[] arrBytes = System.Text.Encoding.UTF8.GetBytes(content);
       using(MemoryStream ms = new MemoryStream())
       {
           BinaryFormatter bf = new BinaryFormatter();
           return bf.Deserialize(ms) as T;        
       }
   }

#endregion
}

序列化对象声明

<font size=2>对类使用序列化时,标注那些不需要序列化的字段。 序列化只能针对字段使用。</font>

[Serializable]
public class MyClass
{
    [Noserialized]
    public string Temp;
    
    [field:Noserialized]    用于标识event不被序列
    public event EventHandler TempChanged;
}

使用序列化相关特性

<font size=2>同时还可以利用特性,在序列化,反序列化执行过程中,自动调用指定的方法,进一步处理序列化数据。例如,可以在执行完反序列化后,自动初始化一些字段。
提供的特性有:

  • OnDeserializedAttribute
  • OnDeserializingAttribute
  • OnSerializedAttribute
  • OnSerializingAttribute
    </font>
using System;
using System.Runtime.Serialization;


[Serializable]
public class SerializableObject
{
    [OnSerializingAttribute]
    virtual protected void OnSerializing(StreamingContext context)
    {

    }

    [OnSerializedAttribute]
    virtual protected void OnSerialized(StreamingContext context)
    {

    }

    [OnDeserializingAttribute]
    virtual protected void OnDeserializing(StreamingContext context)
    {

    }

    [OnDeserializedAttribute]
    virtual protected void OnDeserialized(StreamingContext context)
    {

    }
}

深度定制化ISerializable

如果序列化特性不能满足需求,那就需要使用此接口来自定义化序列化操作。甚至可以序列化为另一个对象。
继承了此接口后,序列化特性就不会生效了。

Person p1 = new Person(){FirstName = "Nick", LastName = "Wang"};
BinarySerializer.SerializeToFile(p1, Application.dataPath, "person.txt");

Person p2 = BinarySerializer.DeserializeFromFile<Person>(System.IO.Path.Combine(Application.dataPath, "person.txt"));
Debug.Log(p2.FirstName);
[Serializable]
public class Person : ISerializable
{
    public string FirstName;
    public string LastName;
    public string ChineseName;

    public Person()
    {

    }

    protected Person(SerializationInfo info, StreamingContext context)
    {
        FirstName = info.GetString("FirstName");
        LastName = info.GetString("LastName");
        ChineseName = string.Format("{0} {1}", LastName, FirstName);        
    }

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("FirstName", FirstName);
        info.AddValue("LastName", LastName);
    }   
}

序列化为另一个对象

Person p1 = new Person(){FirstName = "Nick", LastName = "Wang"};
        BinarySerializer.SerializeToFile(p1, Application.dataPath, "person.txt");
        
        PersonAnother p2 = BinarySerializer.DeserializeFromFile<PersonAnother>(System.IO.Path.Combine(Application.dataPath, "person.txt"));
        Debug.Log(p2.Name);
        
[Serializable]
public class PersonAnother : ISerializable
{
    public string Name;

    public PersonAnother()
    {
    }

    protected PersonAnother(SerializationInfo info, StreamingContext context)
    {
        Name = info.GetString("Name");
    }

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
    }
}

[Serializable]
public class Person : ISerializable
{
    public string FirstName;
    public string LastName;
    public string ChineseName;

    public Person()
    {
    }

    protected Person(SerializationInfo info, StreamingContext context)
    {               
    }

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
        <font color=blue>info.SetType(typeof(PersonAnother));}</font>
        info.AddValue("Name", string.Format("{0} {1}", LastName, FirstName));
    }   
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • JAVA序列化机制的深入研究 对象序列化的最主要的用处就是在传递,和保存对象(object)的时候,保证对象的完整...
    时待吾阅读 10,913评论 0 24
  • 序列化概述 当两个服务在进行通信时,彼此可以发送各种类型的数据。无论是何种类型的数据,都会以字节序列的形式在网络上...
    _张晓龙_阅读 8,213评论 0 11
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,886评论 18 139
  • 点击查看原文 Web SDK 开发手册 SDK 概述 网易云信 SDK 为 Web 应用提供一个完善的 IM 系统...
    layjoy阅读 13,904评论 0 15
  • 01 20出头,每天朝九晚五,这样的生活有意义吗? 好朋友静静大四即将毕业,她的脸上写满了惶恐。 她跟我吐槽道,现...
    熊一一阅读 650评论 0 5