参考:http://www.chinauml.net/developer/DoNet/20040318/231723.html
//此函数可以容许你把任何对象转换为一系列字节,并可以重新转换回对象
public static byte[] RawSerialize( object anything )
{
int rawsize = Marshal.SizeOf( anything );
IntPtr buffer = Marshal.AllocHGlobal( rawsize );
Marshal.StructureToPtr( anything, buffer, false );
byte[] rawdatas = new byte[ rawsize ];
Marshal.Copy( buffer, rawdatas, 0, rawsize );
Marshal.FreeHGlobal( buffer );
return rawdatas;
} public static object RawDeserialize( byte[] rawdatas, Type anytype )
{
int rawsize = Marshal.SizeOf( anytype );
if( rawsize > rawdatas.Length )
return null;
IntPtr buffer = Marshal.AllocHGlobal( rawsize );
Marshal.Copy( rawdatas, 0, buffer, rawsize );
object retobj = Marshal.PtrToStructure( buffer, anytype );
Marshal.FreeHGlobal( buffer );
return retobj;
}
//自动解决数据中每一段的字节排列顺序问题
public static object EndianFlip(object oObject)
{
string sFieldType;
Type tyObject = oObject.GetType();
FieldInfo[] miMembers;
miMembers = tyObject.GetFields();
for (int Looper = miMembers.GetLowerBound(0);
Looper <= miMembers.GetUpperBound(0);
Looper++)
{
sFieldType = miMembers[Looper].FieldType.FullName;
if ((String.Compare(sFieldType, "System.UInt16", true) == 0))
{
ushort tmpUShort;
tmpUShort = (ushort) miMembers[Looper].GetValue(oObject);
tmpUShort = (ushort) (((tmpUShort & 0x00ff) << 8) +
((tmpUShort & 0xff00) >> 8));
miMembers[Looper].SetValue(oObject, tmpUShort);
}
else
if (String.Compare(sFieldType, "System.UInt32", true) == 0)
{
uint tmpInt;
tmpInt = (uint) miMembers[Looper].GetValue(oObject);
tmpInt = (uint) (((tmpInt & 0x000000ff) << 24) +
((tmpInt & 0x0000ff00) << 8) +
((tmpInt & 0x00ff0000) >> 8) +
((tmpInt & 0xff000000) >> 24));
miMembers[Looper].SetValue(oObject, tmpInt);
}
}
return (oObject);
}
本文介绍了一种将对象转换为字节数组的方法,并提供了如何将这些字节数组重新转换回原始对象的技术。此外,还讨论了如何自动解决数据中每一段的字节排列顺序问题。
889

被折叠的 条评论
为什么被折叠?



