.net - Byte = 8bits,但为什么BitConverter不这么认为

标签 .net vb.net

鉴于以下信息

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/

相关文章:

c# - 来电显示检测 : Doesnt work with some phones

.net - 带有 'If' 条件的 VB.NET 'Or' 语句是否双方都进行了评估?

asp.net - 我可以访问 global.asax 中的 Session 变量值吗?

vb.net - Visual Studio 2010 的 VB.NET 代码编辑器中的方法下拉列表是否有键盘快捷键?

.net - .NET 紧凑框架的 GPS 库

.net - COM 互操作是否可能受到 Visual Studio 托管进程的影响?

c# - 用于加载和保存对象的构造函数或静态方法?

C# 项目 : how to update referenced assembly version

c# - 使用 NHibernate 删除树

c# - 有没有一种方法可以组合 2 个 "FileSystem.CopyDirectory"语句,以便我只得到一个进度窗口?