简体   繁体   English

测试对象是否不是类型

[英]Test an object for NOT being a type

I know how to test an object to see if it is of a type, using the IS keyword eg 我知道如何使用IS关键字测试对象是否为某种类型

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

but how do you test for it not being "bar"?, I can't seem to find a keyword that works with IS to test for a negative result. 但是如何测试它是否不是“ bar”呢?我似乎找不到适合IS的关键字来测试否定结果。

BTW - I have a horrible feeling this is soooo obvious, so apologies in advance... 顺便说一句-我感到很恐怖,这很明显,所以提前道歉...

if (!(foo is bar)) {
}

You can also use the as operator . 您也可以使用as运算符

The as operator is used to perform conversions between compatible types. as运算符用于在兼容类型之间执行转换。

bar aBar = foo as bar; // aBar is null if foo is not bar

There is no specific keyword 没有特定的关键字

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

You should clarify whether you want to test that an object is exactly a certain type or assignable from a certain type. 您应该弄清楚您是要测试某个对象是确切的某种类型还是可以从某种类型分配的对象。 For example: 例如:

public class Foo : Bar {}

And suppose you have: 假设您有:

Foo foo = new Foo();

If you want to know whether foo is not Bar(), then you would do this: 如果您想知道foo是否不是Bar(),则可以这样做:

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

But if you want to make sure that foo does not derive from Bar, then an easy check is to use the as keyword. 但是,如果要确保foo不能从Bar派生,那么一个简单的检查就是使用as关键字。

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

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

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