剛剛碰巧群里有人問這個問題,而之前的博客中并沒有提及,打算弄一篇博客簡單提及一下這個知識點。
MSDN文檔中提及了序列化、反序列化的概念,這里引用一下。
序列化:將對象狀態(tài)轉(zhuǎn)換為可保持或傳輸?shù)男问降倪^程。
反序列化:是序列化的逆過程,就是將流轉(zhuǎn)換為對象的過程。
這兩個過程一起保證數(shù)據(jù)易于傳輸和存儲。
詳細的請參考:http://msdn.microsoft.com/zh-cn/library/7ay27kt9(v=vs.100).aspx。
下面直接給出完整的代碼,該代碼演示了如何序列化一個對象以及反序列化(還原對象)的過程。
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Object student = new Student() { StudentID = "007", StudentName = "guwei4037" }; string result = ObjectToString<Object>(student); Console.WriteLine(result + "\r\n"); Student newResult = StringToObject<Student>(result); Console.WriteLine("ID:{0}, Name:{1}", newResult.StudentID, newResult.StudentName); } /// <summary> /// 對象轉(zhuǎn)字符串(序列化后轉(zhuǎn)Base64編碼字符串) /// </summary> /// <param name="obj">對象</param> /// <returns>字符串</returns> public static string ObjectToString<T>(T obj) { using (MemoryStream stream = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, obj); stream.Position = 0; byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); return Convert.ToBase64String(buffer); } } /// <summary> /// 字符串轉(zhuǎn)對象(Base64編碼字符串反序列化為對象) /// </summary> /// <param name="str">字符串</param> /// <returns>對象</returns> public static T StringToObject<T>(string str) { using (MemoryStream stream = new MemoryStream()) { byte[] bytes = Convert.FromBase64String(str); stream.Write(bytes, 0, bytes.Length); stream.Position = 0; IFormatter formatter = new BinaryFormatter(); return (T)formatter.Deserialize(stream); } } } /// <summary> /// 可序列化的類,用Serializable標示此類可序列化 /// </summary> [Serializable] public class Student { public string StudentID { get; set; } public string StudentName { get; set; } } }
運行結(jié)果截圖:
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
當前標題:C#序列化、反序列化-創(chuàng)新互聯(lián)
網(wǎng)站網(wǎng)址:http://sd-ha.com/article2/pgcoc.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設計、響應式網(wǎng)站、定制開發(fā)、企業(yè)建站、營銷型網(wǎng)站建設、網(wǎng)站導航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)