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();
}
object to}
/// <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);
}
}
}
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));
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。