测试对象是否不是类型

时间:2020-03-05 18:51:17  来源:igfitidea点击:

我知道如何使用IS关键字测试对象是否为某种类型。

if (foo is bar)
{
  //do something here
}

但是如何测试它是否不是" bar"呢?我似乎找不到适合IS的关键字来测试否定结果。

顺便说一句,我有一种可怕的感觉,这太明显了,所以提前道歉...

解决方案

回答

if (!(foo is bar)) {
}

回答

没有特定的关键字

if (!(foo is bar)) ...
if (foo.GetType() != bar.GetType()) .. // foo & bar should be on the same level of type hierarchy

回答

我们也可以使用as运算符。

The as operator is used to perform
  conversions between compatible types.
bar aBar = foo as bar; // aBar is null if foo is not bar

回答

我们应该弄清我们是要测试某个对象是确切的某种类型还是可以从某种类型分配的对象。例如:

public class Foo : Bar {}

并假设我们有:

Foo foo = new Foo();

如果我们想知道foo是否不是Bar(),则可以这样做:

if(!(foo.GetType() == tyepof(Bar))) {...}

但是,如果要确保foo不能从Bar派生,那么一个简单的检查就是使用as关键字。

Bar bar = foo as Bar;
if(bar == null) {/* foo is not a bar */}