我应该避免使用 C#“is”运算符进行相等性检查吗?

问题描述

一位同事告诉我,我可以使用 isis not 代替相等运算符 ==!=。我认为 is 运算符与类型有关,the official docs on MSDN 同意,但它也指出:

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

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

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

我认为这是在这里起作用的“表达式模式匹配”(?)。我的问题是,既然使用 is 作为相等运算符 (==) 似乎也适用于值,是否有任何理由避免它?在性能和可读性方面,使用 is 进行所有相等性检查是否合适?

解决方法

除了 x is 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);

(对于完整性:请注意,如果您在两侧都使用文字进行测试,编译器只会将其替换为常量结果。请注意,静态类型将引入必要的空检查)