简体   繁体   English

什么是is-operator的好用法

[英]What is a good usage of the is-operator

What is a good usage of the is-operator? 什么是IS-运营商的一个很好的使用情况?

The construct below for casting is not the recommended way to go, virtually all documentation prefers the as-operator with a null-check. 下面用于转换的构造不是推荐的方法,实际上所有文档都喜欢使用空检查的as-operator。

if(obj is SomeClass)
{
  SomeClass some = (SomeClass)obj;
  ....
}

And sure this is a (very small) performance increase and some even mention the tread safety. 确定这是(非常小的)性能提升,有些甚至提到了胎面安全性。 And yes this is true... 是的,这是真的......

So, why do we have the is-operator? 那么,为什么我们有is-operator?
Where does the "as-operator with a null-check" not work or is not the way to go? “as-operator with a null-check”在哪里不起作用或不是可行的方法?
Does is have an advantage to restrict the scope of you declaration you get by using the is-operator? 通过使用is-operator来限制您声明的范围是否有优势?

as doesn't work with non-nullable struct s: as不能与非可空struct

object o = 123;
int i = o as int; // compile error

however: 然而:

object o = 123;
if(o is int) {
    int i = (int)o;
    //...
}

of course, from 2.0 onwards you could also use: 当然,从2.0开始你也可以使用:

int? i = o as int?;

and test for null like usual. 并像往常一样测试null

There is also the scenario that you don't care about the values of the object... you just need to know what it is: 还有 ,你不关心对象的价值...你只需要知道它是什么情景:

if(obj is Something)
    throw new InvalidOperationException("Seriously, don't do that");
// phew! dodged a bullet; we're ok here...

Note that GetType() is not appropriate for this, as you don't want to have to consider subclasses, interfaces, etc manually. 请注意, GetType()不适用于此,因为您不希望手动考虑子类,接口等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM