C#中实现对象与byte[]间的转换

通过socket来发送信息的时候,它只接受byte[]类型的参数,怎么样把一个对象转为byte[],之后将它通过socket发送呢?

    一、通过序列化将对象转为byte[], 之后再反序化为对象

    public class P2PHelper
     {        /// <summary>
        /// 将一个object对象序列化,返回一个byte[]
        /// </summary>
        /// <param name="obj">能序列化的对象</param>
        /// <returns></returns>
        public static byte[] ObjectToBytes(object obj)
         {
            using (MemoryStream ms = new MemoryStream())
             {
                 IFormatter formatter = new BinaryFormatter();
                 formatter.Serialize(ms, obj);
                return ms.GetBuffer();
             }
         }

        /// <summary>
        /// 将一个序列化后的byte[]数组还原
        /// </summary>
        /// <param name="Bytes"></param>
        /// <returns></returns>
        public static object BytesToObject(byte[] Bytes)
         {
            using (MemoryStream ms = new MemoryStream(Bytes))
             {
                 IFormatter formatter = new BinaryFormatter();
                return formatter.Deserialize(ms);
             }
         }

     }

        这种方法通过序列化来处理对象,虽然简单,然后每一个对象序列化后都至少有256字节, 会导致网络流量的增大。想想,如果一个对象只有10个字节,然而发送的时候却有256字节~~~~~~恐怖(注:多谢 双鱼座 的指正)

        二、使用BitConvert类来处理
      很麻烦的一种方法,我这等懒人是不敢用这种方法的了。不过这篇文章http://pierce.cnblogs.com/archive/2005/06/21/178343.aspx 上有些讲解,想了解的朋友可以去看看。

        三、使用Unsafe方式
       先看代码(尚不知是否有memory leak!!!):

    class   Test
     {
        public static unsafe  byte[] Struct2Bytes(Object obj)
         {
            int size = Marshal.SizeOf(obj);
            byte[] bytes = new byte[size];
            fixed(byte* pb = &bytes[0])
             {
                 Marshal.StructureToPtr(obj,new IntPtr(pb),true);
             }
            return bytes;
         }

        public static unsafe Object Bytes2Struct(byte[] bytes)
         {
            fixed(byte* pb = &bytes[0])
             {
                return Marshal.PtrToStructure(new IntPtr(pb), typeof(Data));
             }
         }
     }

 

转 https://www.cnblogs.com/songjianpin/articles/2404987.html

posted @   dreamw  阅读(4911)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示