標籤:c# post soap協議 持久 stat generic gif text namespace
轉自:https://www.cnblogs.com/lsy131479/p/8371858.html
對象持久化到文字檔,策略是:將對象的屬性值打散,拆解,分別儲存。
序列化:
儲存對象的"全景"
序列化是將對象轉換為可儲存或可傳輸的格式的過程
三種:
二進位序列器:
對象序列化之後是二進位形式的,通過BinaryFormatter類來實現的,這個類位於System.Runtime.Serialization.Formatters.Binary命名空間下
[Serializable] //使對象可序列化(必須添加)
特性
程式集,類,方法,屬性都可以使用特性
Java中註解 <==> C#特性
BinaryFormatter //建立二進位序列化器
Serialize(Stream(流),object(序列化對象))
流:可以理解成打通記憶體和硬碟的一個工具
輸入資料流:從硬碟到記憶體
輸出資料流:從記憶體到硬碟
XML序列化器:
對象序列化之後的結果符合SOAP協議,也就是可以通過SOAP?協議傳輸,通過System.Runtime.Serialization.Formatters.Soap命名空間下的SoapFormatter類來實現的。
SOAP序列化器:
對象序列化之後的結果是XML形式的,通過XmlSerializer?類來實現的,這個類位於System.Xml.Serialization命名空間下。XML序列化不能序列化私人資料。
還原序列化:
將流轉換為對象
Disk(硬碟)--->Cache(記憶體)
BinaryFormatter //建立二進位序列化器
Deserialize(Stream(流))//返回object類型
項目執行個體:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Serializable_Deserialize{ /// <summary> /// 使用者類 /// </summary> //聲明特性 [Serializable] public class UserInfo { public UserInfo() { } public UserInfo(string userName, string userAddress,string path) { UserName = userName; UserAddress = userAddress; Path = path; } public string UserName { get; set; } public string UserAddress { get; set; } public string Path { get; set; } }}
序列化:
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.Serialization.Formatters.Binary;using System.Text;using System.Threading.Tasks;namespace Serializable_Deserialize{ /// <summary> /// 序列化 /// </summary> class Program { static void Main(string[] args) { #region 序列化 //集合初始化器 初始化資料 List<UserInfo> list = new List<UserInfo>() { new UserInfo("房上的貓","北京海澱","https://www.cnblogs.com/lsy131479/"), new UserInfo("傾城月光~淡如水","北京大興","http://www.cnblogs.com/fl72/") }; Console.WriteLine("二進位序列化中..."); //建立檔案流派 Stream stream = new FileStream("save.bin", FileMode.Create); //二進位序列化 BinaryFormatter bf = new BinaryFormatter(); //將對象或具有指定頂級 (根)、 對象圖序列化到給定的流 bf.Serialize(stream, list); //關閉流 stream.Close(); Console.WriteLine("二進位序列化成功!"); #endregion Console.ReadLine(); } }}
還原序列化:
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.Serialization.Formatters.Binary;using System.Text;using System.Threading.Tasks;namespace Serializable_Deserialize{ /// <summary> /// 還原序列化 /// </summary> class Program { static void Main(string[] args) { #region 還原序列化 //建立檔案流派 Stream stream = new FileStream("save.bin", FileMode.Open); //二進位序列化 BinaryFormatter bf = new BinaryFormatter(); //指定的流還原序列化對象圖 List<UserInfo> list = (List<UserInfo>)bf.Deserialize(stream); //遍曆還原序列化後的泛型集合 foreach (UserInfo item in list) { Console.WriteLine(item.UserName + ":" + item.Path); } //關閉流 stream.Close(); #endregion Console.ReadLine(); } }}
【轉】C# 序列化與還原序列化