使用'is'关键字测试null有什么好处? [英] What is the advantage of testing for null using the 'is' keyword?

查看:145
本文介绍了使用'is'关键字测试null有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最近的Visual Studio更新之后,我现在在代码下面出现了一些绿点,表明我可以现代化的地方,并且可能会改进我的代码以使用最新的C#功能。



其中一个建议使用 关键字测试 null 。例如。



不要写...



After a recent Visual Studio update, I am now getting little green dots appearing beneath code, indicating places I could modernise and presumably improve my code to use the latest C# features.

One of these recommends testing for null using the is keyword. Eg.

Don't write...

if( x == null )





改为写这个...





Write this instead...

if( x is null )





我想了解这个的好处,我似乎无法在任何地方找到一个简单的答案。任何人?



我尝试过的事情:



我试过了谷歌搜索,但似乎无法找到一个直接的答案。



I'd like to understand the advantage of this and I don't seem to be able to find a simple answer to this anywhere. Anyone?

What I have tried:

I've tried Googling around but don't seem to be able to find a straight answer.

推荐答案

有一个详细的博客文章可以为你解答:\"is null与C#中的== null [ ^ ]
There is a detailed blog post that can answer this for you: "is null" versus "== null" in C#[^]


我googled== null vs null这是第一个结果



c# - x is null和x == null之间有什么区别? - 堆栈溢出 [ ^ ]



如果您自己搜索,还有更多结果。



主要问题似乎是你可以重载==来改变它的行为,所以当你使用== null时你无法保证实际调用的是什么代码以及== null 正在定义中。例如,如果我有一个Person类,我可以重载== for Person,如果该人没有ID那么它就是null。当你的代码使用if(p == null)时,结果可能是true,尽管变量p实际上并不是空引用。



但是当你使用is时不能重载,所以检查is null可以更准确地查看变量是否为空引用。
I googled "== null vs is null" and this was the first result

c# - What is the difference between "x is null" and "x == null"? - Stack Overflow[^]

There are many more results if you search yourself.

The main issue seems to be that you can overload "==" to change its behaviour so when you use "== null" you have no guarantee what code is actually being called and how "== null" is being defined. For example if I have a Person class I could overload == for Person to say that if the person has no ID then it is null. When your code uses "if (p == null)" the result might be "true" despite the variable "p" not actually being a null reference.

However when you use "is" that can't be overloaded so checking "is null" gives a more accurate view of if the variable is a null reference or not.


见这里: c# - x is之间的区别是什么? null和x == null? - 堆栈溢出 [ ^ ]


这篇关于使用'is'关键字测试null有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆