为什么在.NET中将一个布尔值转换为字节会得到以下输出?
代码片段:
代码片段:
Dim x As Boolean = 1
Dim y As Byte = x 'Implicit conversion here from Boolean to Byte
System.Diagnostics.Debug.Print( _
"x = " & x.ToString _
& " y = " & y.ToString _
& " (bool)(1) = " & CType(1, Boolean).ToString _
& " (byte)((bool)1) = " & CType((CType(1, Boolean)), Byte).ToString)
输出:
x = 真
y = 255
(bool)(1) = 真
(byte)((bool)1) = 255
当将True
(通常被称为1的整数表示)转换为byte
时,为什么会变成255?
ldc.i4 FF 00 00 00
,尽管我看不到规范中说明原因的任何内容。对于非常简单的情况,编译器只是优化掉了转换。 - vcsjonesOption Strict On
来禁用隐式转换。优先使用DirectCast
而不是TryCast
,因为DirectCast
只会进行强制转换,而不会进行类型转换。 - MarkJ