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

VB.NET中’foo = Nothing’和’foo is Nothing’有什么区别?

发布时间:2020-12-17 00:02:41 所属栏目:大数据 来源:网络整理
导读:在 VB.NET,有什么区别 if foo is Nothing Then doStuff()End If 和 if foo=Nothing Then doStuff()End If 更新我收到以下答案: foo is Nothing simply checks if foo is not assigned to any reference. foo = Nothing checks if the reference held by foo
在 VB.NET,有什么区别
if foo is Nothing Then
      doStuff()
End If

if foo=Nothing Then
    doStuff()
End If

更新我收到以下答案:

foo is Nothing simply checks if foo is not assigned to any reference.
foo = Nothing checks if the reference held by foo is equal to nothing.

运行三个语句后,

Dim foo as Object
Dim bar as Integer
foo = bar

foo是Nothing的计算结果为false,而foo = Nothing的计算结果为true.

但是,如果bar被声明为Object而未初始化,则foo为Nothing,foo = Nothing都为true!我认为这是因为Integer是一个值类型而Object是一个引用类型.

这取决于类型.

>对于值类型,Is不起作用,只有=,Nothing引用该类型的默认实例(即通过为给定类型T调用New T()获得的实例).
>对于引用类型,Is执行引用比较(与object.ReferenceEquals(a,Nothing)相同). a =除非为该类明确定义了Operator =,否则通常什么都不起作用.

此外,如果Operator =已经正确实现,那么foo = Nothing和foo Is Nothing应该产生相同的结果(但是对于任何其他值而不是Nothing都是如此)但是foo是没有什么会更有效,因为它是当运算符=将调用方法时编译器内在.
>对于可空值的类型(即Nullable(Of T)的实例),特殊规则适用:与所有其他运算符一样,编译器对基础类型= lifted(注意该博客文章中的错误…).比较两个Nullables的结果因此不是布尔值而是布尔值? (注意?).但是,由于提升运算符的所谓“空传播”,无论foo的值如何,都将返回Nothing.引用Visual Basic 10 language specification(§1.86.3):

If ether (sic!) operand is Nothing,the result of the expression is a value of Nothing typed as the nullable version of the result type.

因此,如果用户想要将Nullable变量与Nothing进行比较,则必须使用foo Is Nothing语法,编译器再次生成特殊代码以使其工作(Visual Basic 10语言规范的§1.79.3).
向Jonathan Allen提示(正确)坚持说我错了;向Jared Parsons提示给我一个Visual Basic 10规范的链接.

(上面假设使用了Option Strict On,因为你总是应该这样.如果不是这种情况,结果会略有不同,因为调用foo = Nothing可能会执行后期绑定调用.)

(编辑:李大同)

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

    推荐文章
      热点阅读