序列化又稱串行化,是.NET運行時環境用來支持用戶定義類型的流化的機制。其目的是以某種存儲形式使自定義對象持久化,或者將這種對象從一個地方傳輸到另一個地方。
.NET框架提供了兩種種串行化的方式:1、是使用BinaryFormatter進行串行化;2、使用XmlSerializer進行串行化。第一種方式提供了一個簡單的二進制數據流以及某些附加的類型信息,而第二種將數據流格式化為XML存儲。 可以使用[Serializable]屬性將類標志為可序列化的。如果某個類的元素不想被序列化,1、可以使用[NonSerialized]屬性來標志,2、可以使用[XmlIgnore]來標志。
序列化意思指的是把對象的當前狀態進行持久化,一個對象的狀態在面向對象的程序中是由屬性表示的,所以序列化類的時候是從屬性讀取值以某種格式保存下來,而類的成員函數不會被序列化,.net存在幾種默認提供的序列化,二進制序列化,xml和json序列化會序列化所有的實例共有屬性。
BinaryFormatter以二進制格式序列化和反序列化對象。
BinaryFormatte序列化:將對象轉化成二進制。
BinaryFormatte反序列化:將二進制轉化為對象。
命名空間: System.Runtime.Serialization.Formatters;
兩個常用的方法:
Deserialize(Stream):將指定的流反序列化成對象
Serialize(Stream, Object):將對象序列化到給定的流
兩個常用的屬性:
Serializable:表示可以被序列化
NonSerializable:屏蔽被序列化
例如:
using UnityEngine; using System; using System.Collections; using System.IO; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; [Serializable] // 表示該類可以被序列化 class Person { private string name; [NonSerialized] // 表示下面這個age字段不進行序列化 private int age; public string Name { get { return name;} set { name = value;} } public int Age { get { return age;} set { age = value;} } public Person() { } public Person(string name, int age) { this.name = name; this.age = age; } public void SayHi() { Debug.LogFormat ("我是{0}, 今年{1}歲", name, age); } } public class BinarySerializer : MonoBehaviour { string filePath = Directory.GetCurrentDirectory() + "/binaryFile.txt"; // Use this for initialization void Start () { List<Person> listPers = new List<Person> (); Person per1 = new Person ("張三", 18); Person per2 = new Person ("李四", 20); listPers.Add (per1); listPers.Add (per2); SerializeMethod (listPers); // 序列化 DeserializeMethod(); // 反序列化 Debug.Log("Done ! "); } void DeserializeMethod() // 二進制反序列化 { FileStream fs = new FileStream (filePath, FileMode.Open); BinaryFormatter bf = new BinaryFormatter (); List<Person> list = bf.Deserialize (fs) as List<Person>; if (list != null) { for (int i = 0; i < list.Count; i++) { list [i].SayHi (); } } fs.Close (); } void SerializeMethod(List<Person> listPers) // 二進制序列化 { FileStream fs = new FileStream (filePath, FileMode.Create); BinaryFormatter bf = new BinaryFormatter (); bf.Serialize (fs, listPers); fs.Close (); } // Update is called once per frame void Update () { } }
序列化的文本打開后,內容如下所示:
NonSerialized作用:被標記的字段都賦成空

反序列化輸出結果:
大家好,我是張三,今年0歲
大家好,我是李四,今年0歲
由此看出,未序列化的字段存儲的值為空
文章轉載自:https://blog.csdn.net/e295166319/article/details/52790131、https://blog.csdn.net/u013667895/article/details/78478458
