c#中对object进行序列化和反序列化

10 篇文章 0 订阅

有时候我们需要对一些数据进行二进制序列化以达到保存或传输的目的,这里记录一下对object的序列化和反序列化操作。


首先引入命名空间:

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
object的序列化和反序列化
	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"]);
    }

结果:


注意:需要序列化的类一定要使用[Serializable]对其进行标记.




  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值