前段时间测试一个P2P程序,通过UDP来发送数据。UdpClient.Send(..)方法需要一个byte[]这样的参数。想当年用c++Builder的时候,只需要用强制转换就行了。如今时过境迁,.net平台上处理这事却似乎有些麻烦!今天恰好在csdn上见一帖,又看到了另一种处理方法,^_^, 现将我所知的3种方法总结一下。
一、通过序列化将对象转为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);
}
}
}
{ /// <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);
}
}
}
二、使用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));
}
}
}
{
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));
}
}
}
倘若还有其它方法,请告之,:)