gpt4 book ai didi

.net - VB.NET: bool 值来自 `Nothing` 有时是 `false` 有时是 Nullreference-Exception

转载 作者:行者123 更新时间:2023-12-04 04:58:07 25 4
gpt4 key购买 nike

来自 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)) 。我认为这是因为编译器使用了辅助函数,但这不是我的主题。

为什么要类型转换 NothingBoolean计算结果为 False , 而转换一个对象是 NothingBoolean抛出一个空引用异常?那有意义吗?
[Option Strict ON]

最佳答案

大概是因为 Nothing 在 VB.NET 中与 null 不完全相同在 C# 中。

对于值类型,Nothing暗示该类型的默认值。在 Boolean 的情况下,默认值为 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.
    –The Truth about Nullable Types and VB...



编辑 :为了进一步澄清,第二个示例抛出 NullReferenceException 的原因在运行时是因为 CLR 试图拆箱 Object (引用类型)到 Boolean .这当然失败了,因为对象是用空引用初始化的(将其设置为等于 Nothing):
Dim obj As Object = Nothing

请记住,正如我上面所解释的,VB.NET 关键字 Nothing仍然以与 null 相同的方式工作在 C# 中,当涉及到引用类型时。这就解释了为什么您会收到 NullReferenceException因为您尝试转换的对象实际上是一个空引用。它根本不包含值,因此无法拆箱为 Boolean类型。

当您尝试强制转换关键字 Nothing 时,您不会看到相同的行为。到 bool 值,即:
Dim b As Boolean = DirectCast(Nothing, Boolean)

因为关键字 Nothing (这次,在值类型的情况下)仅表示“此类型的默认值”。在 Boolean 的情况下, 那是 False ,因此类型转换合乎逻辑且直截了当。

关于.net - VB.NET: bool 值来自 `Nothing` 有时是 `false` 有时是 Nullreference-Exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4804318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com