gpt4 book ai didi

c# - "x is null"和 "x == null"有什么区别?

转载 作者:IT王子 更新时间:2023-10-29 03:29:54 26 4
gpt4 key购买 nike

在C# 7中,我们可以使用

if (x is null) return;

代替

if (x == null) return;

与旧方法相比,使用新方法(前面的例子)有什么优势吗?

语义有什么不同吗?

这只是品味问题吗?如果不是,我应该什么时候使用一个而不是另一个?

引用:What’s New in C# 7.0 .

最佳答案

更新:Roslyn 编译器已更新,在没有重载相等运算符时 使两个运算符的行为相同。请参阅code in the current compiler results (代码中的 M1M2)显示了没有重载相等比较器时会发生什么。它们现在都具有性能更好的 == 行为。如果有一个重载的相等比较器,the code still differs .

对于旧版本的 Roslyn 编译器,请参阅以下分析。


对于 null,这与我们在 C# 6 中所习惯的没有区别。但是,当您将 null 更改为另一个常量时,事情会变得有趣。

以此为例:

Test(1);

public void Test(object o)
{
if (o is 1) Console.WriteLine("a");
else Console.WriteLine("b");
}

测试产生a。如果将其与您通常编写的 o == (object)1 进行比较,它确实有很大的不同。 is 考虑了比较另一端的类型。太酷了!

我认为 == nullis null 常量模式只是“偶然”非常熟悉的东西,其中 的语法是 运算符和等于运算符产生相同的结果。


作为svick评论,is null calls System.Object::Equals(object, object) where == calls ceq .

IL :

IL_0000: ldarg.1              // Load argument 1 onto the stack
IL_0001: ldnull // Push a null reference on the stack
IL_0002: call bool [mscorlib]System.Object::Equals(object, object) // Call method indicated on the stack with arguments
IL_0007: ret // Return from method, possibly with a value

== 的 IL:

IL_0000: ldarg.1              // Load argument 1 onto the stack
IL_0001: ldnull // Push a null reference on the stack
IL_0002: ceq // Push 1 (of type int32) if value1 equals value2, else push 0
IL_0004: ret // Return from method, possibly with a value

因为我们谈论的是null,所以没有区别,因为only makes a difference on instances .当您重载相等运算符时,这可能会改变。

关于c# - "x is null"和 "x == null"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40676426/

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