我知道如何使用 IS 关键字来测试一个对象以查看它是否属于某种类型,例如

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

但是你如何测试它不是“bar”?,我似乎找不到与 IS 一起使用的关键字来测试负面结果。

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

有帮助吗?

解决方案

if (!(foo is bar)) {
}

其他提示

您还可以使用 作为操作员.

AS运算符用于在兼容类型之间执行转换。

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

没有特定的关键字

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

你应该澄清你是否想测试一个对象是 确切地 某种类型或 可分配的 来自某种类型。例如:

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 */}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top