在 VB.NET 中将布尔值转换为整数 [英] Convert Boolean to Integer in VB.NET

查看:52
本文介绍了在 VB.NET 中将布尔值转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取以下代码:

Sub Main()

    Dim i As Integer
    Dim b As Boolean

    i = 1
    b = i
    i = b
    Console.WriteLine(i)

    i = Convert.ToInt32(b)
    Console.WriteLine(i)

End Sub

这将打印以下内容:

-1
1

这是为什么?

(开个玩笑:)你也可以得到 0...

(Just a joke :) You can get 0 too...

Int32.TryParse("True", i)
Console.WriteLine(i)

推荐答案

您所看到的是一些遗留代码.

What you're seeing is a bit of legacy code showing its head.

问题的核心是 VT_BOOL 类型.Visual Basic 6.0 使用 VT_BOOL 类型(AKA VARIANT_BOOL)作为其布尔值.VARIANT_BOOL 的 True 用值 VARIANT_TRUE 表示,该值具有整数值 -1.在转换为 .NET 期间,决定在使用 Visual Basic 转换例程转换布尔值时value 为 Integer 值,Visual Basic 6.0 语义将保留在返回值上;它将是 -1.

At the heart of the matter is the VT_BOOL type. Visual Basic 6.0 used the VT_BOOL type (AKA VARIANT_BOOL) for its boolean values. True for a VARIANT_BOOL is represented with the value VARIANT_TRUE which has the integer value -1. During the conversion to .NET it was decided that when using Visual Basic conversion routines to convert a boolean value to an Integer value, Visual Basic 6.0 semantics would be maintained on the return value; it would be -1.

第一次隐式转换发生在 b = i 行中.在幕后,这进行了从整数到布尔值的隐式转换.任何非零值都被认为是真的,因此结果值是真的.

The first implicit conversion occurs with the b = i line. Under the hood this does an implicit conversion from integer to boolean. Any non-zero value is deemed to be true, therefore the resulting value is true.

但是,以下代码行将隐式转换为整数类型.

However, the following line of code is doing an implicit conversion to an integer type.

i = b

在幕后,它使用 Visual Basic 转换例程之一 (CTypeCInt) 将值转换为整数.因此,Visual Basic 语义在起作用,返回的值为 -1.

Under the hood this uses one of the Visual Basic conversion routines (CType or CInt) to convert the value to an integer. As such Visual Basic semantics are in play and the value returned is -1.

下一个有趣的行是 Convert.ToInt32() 行.这是使用不使用 Visual Basic 语义的 .NET 转换例程.相反,它返回基础 BCL 表示为 1 的真实布尔值.

The next interesting line is the Convert.ToInt32() line. This is using a .NET conversion routine which does not use Visual Basic semantics. Instead, it returns the underlying BCL representation for a true boolean value which is 1.

这篇关于在 VB.NET 中将布尔值转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆