生活随笔
收集整理的這篇文章主要介紹了
C# 二进制BinaryFormatter进行序列化与反序列化
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
原文鏈接:https://blog.csdn.net/e295166319/article/details/52790131
序列化又稱串行化,是.NET運(yùn)行時(shí)環(huán)境用來支持用戶定義類型的流化的機(jī)制。其目的是以某種存儲(chǔ)形成使自定義對(duì)象持久化,或者將這種對(duì)象從一個(gè)地方傳輸?shù)搅硪粋€(gè)地方。
.NET框架提供了兩種種串行化的方式:1、是使用BinaryFormatter進(jìn)行串行化;2、使用XmlSerializer進(jìn)行串行化。第一種方式提供了一個(gè)簡單的二進(jìn)制數(shù)據(jù)流以及某些附加的類型信息,而第二種將數(shù)據(jù)流格式化為XML存儲(chǔ)。??? 可以使用[Serializable]屬性將類標(biāo)志為可序列化的。如果某個(gè)類的元素不想被序列化,1、可以使用[NonSerialized]屬性來標(biāo)志,2、可以使用[XmlIgnore]來標(biāo)志。
序列化意思指的是把對(duì)象的當(dāng)前狀態(tài)進(jìn)行持久化,一個(gè)對(duì)象的狀態(tài)在面向?qū)ο蟮某绦蛑惺怯蓪傩员硎镜?#xff0c;所以序列化類的時(shí)候是從屬性讀取值以某種格式保存下來,而類的成員函數(shù)不會(huì)被序列化,.net存在幾種默認(rèn)提供的序列化,二進(jìn)制序列化,xml和json序列化會(huì)序列化所有的實(shí)例共有屬性。
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] 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"; 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 ();} void Update () { }}
序列化的文本打開后,內(nèi)容如下所示:
反序列化輸出結(jié)果:
大家好,我是張三,今年0歲
大家好,我是李四,今年0歲
由此看出,未序列化的字段存儲(chǔ)的值為空
關(guān)于XmlSerializer進(jìn)行序列化與反序列化的操作將在下篇文章進(jìn)行介紹……
總結(jié)
以上是生活随笔為你收集整理的C# 二进制BinaryFormatter进行序列化与反序列化的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。