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
}

序列化對(duì)象聲明

<font size=2>對(duì)類使用序列化時(shí),標(biāo)注那些不需要序列化的字段。 序列化只能針對(duì)字段使用。</font>

[Serializable]
public class MyClass
{
    [Noserialized]
    public string Temp;
    
    [field:Noserialized]    用于標(biāo)識(shí)event不被序列
    public event EventHandler TempChanged;
}

使用序列化相關(guān)特性

<font size=2>同時(shí)還可以利用特性,在序列化,反序列化執(zhí)行過(guò)程中,自動(dòng)調(diào)用指定的方法,進(jìn)一步處理序列化數(shù)據(jù)。例如,可以在執(zhí)行完反序列化后,自動(dòng)初始化一些字段。
提供的特性有:

  • 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

如果序列化特性不能滿足需求,那就需要使用此接口來(lái)自定義化序列化操作。甚至可以序列化為另一個(gè)對(duì)象。
繼承了此接口后,序列化特性就不會(huì)生效了。

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);
    }   
}

序列化為另一個(gè)對(duì)象

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));
    }   
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • JAVA序列化機(jī)制的深入研究 對(duì)象序列化的最主要的用處就是在傳遞,和保存對(duì)象(object)的時(shí)候,保證對(duì)象的完整...
    時(shí)待吾閱讀 11,224評(píng)論 0 24
  • 序列化概述 當(dāng)兩個(gè)服務(wù)在進(jìn)行通信時(shí),彼此可以發(fā)送各種類型的數(shù)據(jù)。無(wú)論是何種類型的數(shù)據(jù),都會(huì)以字節(jié)序列的形式在網(wǎng)絡(luò)上...
    _張曉龍_閱讀 8,395評(píng)論 0 11
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,711評(píng)論 19 139
  • 點(diǎn)擊查看原文 Web SDK 開(kāi)發(fā)手冊(cè) SDK 概述 網(wǎng)易云信 SDK 為 Web 應(yīng)用提供一個(gè)完善的 IM 系統(tǒng)...
    layjoy閱讀 14,495評(píng)論 0 15
  • 01 20出頭,每天朝九晚五,這樣的生活有意義嗎? 好朋友靜靜大四即將畢業(yè),她的臉上寫(xiě)滿了惶恐。 她跟我吐槽道,現(xiàn)...
    熊一一閱讀 709評(píng)論 0 5

友情鏈接更多精彩內(nèi)容