首页 > 解决方案 > 我应该避免使用 C#“is”运算符进行相等检查吗?

问题描述

一位同事告诉我,我可以使用isandis not代替相等运算符==and !=。我认为is操作符与类型有关,MSDN 上的官方文档也同意,但它也指出:

从 C# 7.0 开始,您还可以使用 is 运算符将表达式与模式匹配

我不认为检查值is会起作用,但奇怪的是:

> "tomato" is "apple"
false
> 1 is not 2
true

我认为这是在这里工作的“表达式模式匹配”(?)。我的问题是,既然is用作相等运算符 ( ==) 似乎也适用于值,有什么理由避免它吗?在性能和可读性方面,将其is用于所有相等性检查会好吗?

标签: c#c#-7.0

解决方案


除了x is null它们是相同的并且对于恒定值的品味问题。如评论中所述,模式匹配仅适用于常量。检查 null 的特殊情况保证不使用任何重载的相等运算符。我用 ILSpy 进行了交叉检查:

原始源代码:

string tomatoString = "tomato";
object tomatoObj = "tomato";
Console.WriteLine(tomatoString.Equals("tomato"));
Console.WriteLine(tomatoString is "tomato");
Console.WriteLine(tomatoObj is "tomato");
Console.WriteLine("tomato" is "tomato");
Console.WriteLine(tomatoString is null);

用 ILSpy 反编译:

string tomatoString = "tomato";
object tomatoObj = "tomato";
Console.WriteLine(tomatoString.Equals("tomato"));
Console.WriteLine(tomatoString == "tomato");
string text = tomatoObj as string;
Console.WriteLine(text != null && text == "tomato");
Console.WriteLine(value: true);
Console.WriteLine(tomatoString == null);

(为了完整性:注意,如果你在两边都用文字测试它,编译器只会用它的常量结果替换它。注意静态类型会引入必要的空检查)


推荐阅读