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