使用C#获取Int/short /字节结构字节表示

2 c# reflection marshalling binary-data

给定一个FieldInfo对象和一个对象,我需要得到该字段的实际字节表示.我知道这个领域要么是int,Int32,uint,short等等.

如何获得实际的字节表示?BinaryFormatter.Serialize无济于事,因为它会给我提供比我需要的更多信息(它还记录类型名称等).该Marshal级似乎不具备设施使用的字节数组(但也许我失去了一些东西).

谢谢

Jam*_*ran 7

使用BitConverter.GetBytes()

您首先必须将值转换为它的本机类型,而不是使用BitConverter来获取字节:

byte[] Bytes;

if (valType == typeof(int))
{
    int intVal = (int) GetFieldValue(....);
    Bytes = BitConverter.GetBytes(intVval);
} 
else if (valType == typeof(long))
{
    int lngVal = (long) GetFieldValue(....);
    Bytes = BitConverter.GetBytes(lngVal);
} else ....
Run Code Online (Sandbox Code Playgroud)