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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM