10年6个月前IP:江苏
821213
2楼

/// <summary> /// 结构体 值类型转byte数组 /// BitConverter /// </summary> /// <typeparam name="T"></typeparam> /// <param name="structObj"></param> /// <returns></returns> public static byte[] StructToBytes<T>(this T structObj) where T : struct { int size = System.Runtime.InteropServices.Marshal.SizeOf(structObj); byte[] bytes = new byte[size];

        IntPtr structPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(size);
        System.Runtime.InteropServices.Marshal.StructureToPtr(structObj, structPtr, true);
        System.Runtime.InteropServices.Marshal.Copy(structPtr, bytes, 0, size);
        System.Runtime.InteropServices.Marshal.FreeHGlobal(structPtr);
        return bytes;
    }
    /// <summary>
    /// byte数组转 结构体 值类型
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="bytes">
    /// <returns></returns>
    public static T BytesToStuct<t>(this byte[] bytes) where T : struct
    {
        int size = System.Runtime.InteropServices.Marshal.SizeOf(default(T));
        if (size > bytes.Length)
        {
            return default(T);
        }
        IntPtr structPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(size);
        System.Runtime.InteropServices.Marshal.Copy(bytes, 0, structPtr, size);
        T obj = (T)System.Runtime.InteropServices.Marshal.PtrToStructure(structPtr, typeof(T));
        System.Runtime.InteropServices.Marshal.FreeHGlobal(structPtr);

        return obj;
    }
</t>

/// <summary> /// 把对象序列化并返回相应的字节 /// </summary> /// <param name="pObj">需要序列化的对象</param> /// <returns>byte[]</returns> static public byte[] SerializeObject(this object pObj) { if (pObj == null) return null; XXXXXXXXX.MemoryStream _memory = new XXXXXXXXX.MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(_memory, pObj); _memory.Position = 0; byte[] read = new byte[_memory.Length]; _memory.Read(read, 0, read.Length); _memory.Close(); return read; }

    /// <summary>
    /// 把字节反序列化成相应的对象
    /// </summary>
    /// <param name="pBytes">字节流
    /// <returns>object</returns>
    static public T DeserializeObject<t>(this byte[] pBytes)
    {
        T _newOjb ;
        if (pBytes == null || pBytes.Length < 1) return default(T);
        System.IO.MemoryStream _memory = new System.IO.MemoryStream(pBytes);
        _memory.Position = 0;
        BinaryFormatter formatter = new BinaryFormatter();
        _newOjb = (T)formatter.Deserialize(_memory);
        _memory.Close();
        return _newOjb;
    }
</t>
评论
文号 / 821213

千古风流
名片专栏发私信
学术分 1
总主题 146 帖总回复 1873 楼拥有证书:进士 学者 机友 笔友
注册于 2010/12/30 03:32:26最后登录 2026/06/20 19:33:53
主体类型:个人
所属领域:无
认证方式:手机号
IP归属地:0

个人简介

暂未填写
笔记
{{note.content}}
{{n.user.username}}
{{fromNow(n.toc)}} {{n.status === noteStatus.disabled ? "已屏蔽" : ""}} {{n.status === noteStatus.unknown ? "正在审核" : ""}} {{n.status === noteStatus.deleted ? '已删除' : ''}}
  • 编辑
  • 删除
  • {{n.status === 'disabled' ? "解除屏蔽" : "屏蔽" }}
我也是有底线的