“x is null”和“x == null”的区别是什么? 返回

C#论坛 老数据
2 2053
该叫什么 wj01 发布于2021/4/11
悬赏:5 飞吻

使用新方法(前一个例子)比使用旧方法有什么优势吗?
语义有什么不同吗?
这只是个人喜好的问题吗?如果没有,什么时候我应该使用其中一个? 

热忱回答2

  • image.png

    当您尝试比较非空变量和空值时,也会有区别。当使用==时,编译器将发出警告,而当使用is时,编译器将发出错误。



    IS还能判段类型

    if (i is string) { 
                
    }


    大多数情况下(99%的情况下相同) 

    0 回复
  • is operator - C# reference | Microsoft Docs

    还有一个区别:When you match an expression against null, the compiler guarantees that no user-overloaded == or != operator is invoked

    即:当重载了运算符==时,==null会调用重载方法。而is null绝对不会调用重载的==方法

    0 回复