鉴于以下信息
Public Enum Request As Byte
None = 0
Identity = 1
License = 2
End Enum
Protected mType As Communication.Request
mType = Communication.Request.Identity
Debug.Print (BitConverter.GetBytes(mType).Length.tostring)
2
为什么 bitconverter 报告 mType 的长度为 2。我本以为将 Byte 传递到 BitConverter.GetBytes 只会返回该 Byte。
我的意思是这没什么大不了的,因为它只是通过 TCP 套接字发送一个非常小的数据 block ,但我只是很好奇为什么它认为它是 2 个字节。
最佳答案
由于 BitConverter.GetBytes(Byte b) 没有重载(请参阅 msdn ),因此使用最接近的可用隐式重载,在本例中返回一个 byte[2]。
使用简单的代码:
byte b = 1;
BitConverter.GetBytes(b);
编译它并使用 ildasm,我们看到调用了 int16(这是一个短整型)的方法:
.method public hidebysig instance void bytetest() cil managed
{
// Code size 11 (0xb)
.maxstack 1
.locals init ([0] uint8 b)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: call uint8[] [mscorlib]System.BitConverter::GetBytes(int16)
IL_0009: pop
IL_000a: ret
} // end of method Test::bytetest
将方法悬停在 Visual Studio 中时也可以看到(选定的重载显示在工具提示中)
关于.net - Byte = 8bits,但为什么BitConverter不这么认为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2604788/