C#中的數據對象序列化代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Model
{public class SerializationUnit { /// <summary> /// 把對象序列化為字節數組 /// </summary> public static byte[] SerializeObject(object obj) { if (obj == null) return null; //內存實例 MemoryStream ms = new MemoryStream(); //創建序列化的實例 BinaryFormatter formatter = new BinaryFormatter(); long size = ms.GetBuffer().Length; formatter.Serialize(ms, obj);//序列化對象,寫入ms流中 ms.Position = 0; //byte[] bytes = new byte[ms.Length];//這個有錯誤 byte[] bytes = ms.GetBuffer(); ms.Read(bytes, 0, bytes.Length); ms.Close(); return bytes; } /// <summary> /// 把字節數組反序列化成對象 /// </summary> public static object DeserializeObject(byte[] bytes) { object obj = null; if (bytes == null) return obj; //利用傳來的byte[]創建一個內存流 MemoryStream ms = new MemoryStream(bytes); ms.Position = 0; BinaryFormatter formatter = new BinaryFormatter(); obj = formatter.Deserialize(ms);//把內存流反序列成對象 ms.Close(); return obj; } /// <summary> /// 把字典序列化 /// </summary> /// <param name="dic"></param> /// <returns></returns> public static byte[] SerializeDic(Dictionary<string, object> dic) { if (dic.Count == 0) return null; MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, dic);//把字典序列化成流 byte[] bytes = new byte[ms.Length];//從流中讀出byte[] ms.Read(bytes, 0, bytes.Length); return bytes; } /// <summary> /// 反序列化返回字典 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static Dictionary<string, object> DeserializeDic(byte[] bytes) { Dictionary<string, object> dic = null; if (bytes == null) return dic; //利用傳來的byte[]創建一個內存流 MemoryStream ms = new MemoryStream(bytes); ms.Position = 0; BinaryFormatter formatter = new BinaryFormatter(); //把流中轉換為Dictionary dic = (Dictionary<string, object>)formatter.Deserialize(ms); return dic; } } } </pre><br />
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!