2010-04-09 22 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