2010-04-09 62 views
2

考虑以下信息字节= 8位,但为什么不BitConverter这么认为

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报告说,M型是我本来以为是2的长度传递一个字节到BitConverter.GetBytes只会返回字节。

我的意思是没什么大不了的,因为它只是通过一个TCP套接字发送一个非常小的数据块,但我只是很好奇它为什么认为它是2个字节。

+0

你真是幸运,一个字节是8的倍数。有时它是6,7或9位。 – WhirlWind 2010-04-09 02:48:29

回答

6

因为存在用于BitConverter.GetBytes(字节B)没有过载(见msdn),最近的可用的隐式过载被使用,其在这种情况下,返回一个字节[2]。

使用简单的代码:

 byte b = 1; 
     BitConverter.GetBytes(b); 

编译这一点,并使用反汇编,我们看到了一个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中(选定的超载显示在工具提示中)

+0

多数民众赞成在一个错误,因为我想使它动态计算我的大小使用bitconverter ...猜我需要做手动当我的枚举是字节 – 2010-04-09 03:00:39

+3

写一个扩展方法扩展BitConverter并让它返回 新字节[1 ] {输入}。 – Femaref 2010-04-09 03:10:23

+0

@Femaref,这是一个很好的想法。但[它似乎不可能](http://stackoverflow.com/questions/249222/can-i-add-extension-methods-to-an-existing-static-class) – kdbanman 2015-08-04 21:17:55