加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-17 00:02:22 所属栏目:大数据 来源:网络整理
导读:从 Basic boolean logic in C#开始,我想知道为什么: Dim b As BooleanDim 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 = D
从 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(这次,在值类型的情况下)仅仅意味着“此类型的默认值”.在布尔值的情况下,这是假的,因此转换是合乎逻辑且直截了当的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读