c# - 我应该避免使用 C#“is”运算符进行相等检查吗?
问题描述
一位同事告诉我,我可以使用is
andis not
代替相等运算符==
and !=
。我认为is
操作符与类型有关,MSDN 上的官方文档也同意,但它也指出:
从 C# 7.0 开始,您还可以使用 is 运算符将表达式与模式匹配
我不认为检查值is
会起作用,但奇怪的是:
> "tomato" is "apple"
false
> 1 is not 2
true
我认为这是在这里工作的“表达式模式匹配”(?)。我的问题是,既然is
用作相等运算符 ( ==
) 似乎也适用于值,有什么理由避免它吗?在性能和可读性方面,将其is
用于所有相等性检查会好吗?
解决方案
除了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);
(为了完整性:注意,如果你在两边都用文字测试它,编译器只会用它的常量结果替换它。注意静态类型会引入必要的空检查)
推荐阅读
- python - Numpy - 将 3D 数组(100,100,3)与 2D 数组(100,100)相乘
- javascript - 编写 reactJS 网页标记的所有选项有哪些?
- python - Django,使用字典列表的响应
- react-native - 我正在尝试安装 axios 但发生了这样的错误
- javascript - odoo 11 不加载 javascript 代码
- reactjs - 从 material-ui 日期选择器中删除年份
- android - 在 kotlin 的另一个线程中运行 Room Insert 的推荐方法
- javascript - Socket.on 内的 socket.on
- websocket - 带有 JWT 身份验证的 NGINX 反向代理 WebSockets 没有 Access-Control-Allow-Origin 标头
- bbc-microbit - micro:bit 上的按钮 B 总是被按下