C# 內存流(MemoryStream)的對象序列化

直接上代碼:

命名空間:

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

實現函數:

	public static byte[] SerializeObject(object obj)
	{
		if (obj == null)
			return null;
		//內存實例
		MemoryStream ms = new MemoryStream();
		//創建序列化的實例
		BinaryFormatter formatter = new BinaryFormatter();
		formatter.Serialize(ms, obj);//序列化對象,寫入ms流中  
		byte[] bytes = ms.GetBuffer();
		return bytes;
	}
	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;
	}

測試方法:

    public static void SerializeDicTest(){
        
        Dictionary<string, int> test = new Dictionary<string, int>();
        
        test.Add("1",1);
        test.Add("2",2);
        test.Add("3",4);
        
        byte[] testbyte = Tools.SerializeObject(test);
        
        Dictionary<string, int> testdic = (Dictionary<string, int>)Tools.DeserializeObject(testbyte);
        
        Debug.Log("[SerializeDicTest]  : " + testdic["3"]);
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章