VB.NET:来自`Nothing`的布尔值有时是`false`,有时是Nullreference-Exception

前端之家收集整理的这篇文章主要介绍了VB.NET:来自`Nothing`的布尔值有时是`false`,有时是Nullreference-Exception前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Basic boolean logic in C#开始,我想知道为什么:
Dim b As Boolean
Dim obj As Object = Nothing
'followig evaluates to False'
b = DirectCast(Nothing,Boolean)
'This throws an "Object reference not set to an instance of an object"-Exception'
b = DirectCast(obj,Boolean)

CType(obj,Boolean)将计算为False(就像CBool​​(obj)).我认为这是因为编译器使用了辅助函数,但这不是我的主题.

为什么将Nothing转换为布尔值为False,而将Nothing的对象转换为布尔值会抛出Nullreference-Exception?那有意义吗?

[Option Strict ON]
据推测,这是因为VB.NET中的 Nothing与C#中的null不完全相同.

在值类型的情况下,Nothing意味着该类型的默认值.在布尔值的情况下,默认值为False,因此转换成功.

One of the primary differences between value types such as Integer or structures and reference types such as Form or String is that reference types support a null value. That is to say,a reference type variable can contain the value Nothing,which means that the variable doesn’t actually refer to a value. In contrast,a value type variable always contains a value. An Integer variable always contains a number,even if that number is zero. If you assign the value Nothing to a value type variable,the value type variable just gets assigned its default value (in the case of Integer,that default value is zero). There is no way in the current CLR to look at an Integer variable and determine whether it has never been assigned a value – the fact that it contains zero doesn’t necessarily mean that it hasn’t been assigned a value.

–07001

编辑:为了进一步说明,第二个示例在运行时抛出NullReferenceException的原因是因为CLR正在尝试将Object(引用类型)解包为Boolean.当然,这会失败,因为对象是使用null引用初始化的(将其设置为Nothing):

Dim obj As Object = Nothing

请记住,正如我上面所解释的,当涉及引用类型时,VB.NET关键字Nothing仍然与C#中的null相同.这就解释了为什么你得到一个NullReferenceException,因为你试图强制转换的对象实际上是一个空引用.它根本不包含任何值,因此不能取消装箱为布尔类型.

当您尝试将关键字Nothing转换为布尔值时,您看不到相同的行为,即:

Dim b As Boolean = DirectCast(Nothing,Boolean)

因为关键字Nothing(这次,在值类型的情况下)仅仅意味着“此类型的默认值”.在布尔值的情况下,这是假的,因此转换是合乎逻辑且直截了当的.

猜你在找的VB相关文章