关于C#序列化结果的长度获取

    关于C#序列化的文章真的是好多,但是内容大致一样,主要分四类:

  1. BinarySerialize
  2. SoapSerialize
  3. XmlSerialize
  4. JSON.Net和DataContractJsonSerializer

    最近的一个项目需要使用Socket进行通信,所以必然涉及序列化的问题。使用BinarySerialize序列化之后发现无论如何获取不了序列化后的实际长度,代码如下

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Serialize
{
    public class BinarySerialize
    {
        byte[] buffer=new byte[1024];

        public void Serialize(Book book)
        {
            using (MemoryStream fs = new MemoryStream(buffer, 0,1024))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fs, book);
            }
        }

        public Book DeSerialize()
        {
            Book book;
            using (MemoryStream fs = new MemoryStream(buffer,0,1024))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                book = (Book)formatter.Deserialize(fs);
            }
            return book;
        }
    }
}

    通过MemoryStream获取长度,永远是1024。后来试了好久发现其实只需要改一点点地方就可以了,改正后的代码如下,顺便做了点通用性扩展:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;


namespace Serialize
{
    public class MemoryBinarySerialize
    {
        
        public static byte[] Serialize(object obj)
        {
            MemoryStream fs = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(fs, obj);
            return fs.GetBuffer();
        }
        
        public static object DeSerialize(byte[] data)
        {
            MemoryStream fs = new MemoryStream(data);
            BinaryFormatter formatter = new BinaryFormatter();
            object obj= formatter.Deserialize(fs);
            return obj;
        }
    }
}

    参考文献:

    C#序列化技术详解(转):http://www.cnblogs.com/ejiyuan/archive/2009/01/21/1379256.html

    序列化和反序列化(Socket中传递Object):http://dev.firnow.com/course/4_webprogram/asp.net/netjs/20081011/150063.html

    C#中JSON的序列化和反序列化:http://www.dotnetdev.cn/2010/01/c%E4%B8%AD%E7%9A%84json%E7%9A%84%E5%BA%8F%E5%88%97%E5%8C%96%E5%92%8C%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96/

转载于:https://www.cnblogs.com/sdqxcxh/archive/2011/01/19/1939101.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值