我希望检查一个对象是否不是某种特定类型。我知道如何检查某个东西是否是某种特定类型:
但是。
if (t is TypeA)
{
...
}
但是。
if (t isnt TypeA)
{
...
}
无法正常工作。
更新于2020年10月30日:
时代在变化。从C# 9.0开始,您可以使用更自然的方式进行检查:
if(t is not TypeA) { ... }
翻译后的文本:
C# 并不是很接近自然语言 ;) 使用这个。
if(!(t is TypeA))
{
...
}
扩展方法来拯救!!
public static class ObjectExtensions
{
public static bool Isnt(this object source, Type targetType)
{
return source.GetType() != targetType;
}
}
用法
if (t.Isnt(typeof(TypeA)))
{
...
}
简短回答:您可能想使用:
if (t.GetType()==typeof(TypeA))
{
...
}
if (t.GetType()!=typeof(TypeA))
{
...
}
长答案:
所以,要知道你问的是否是特定类型。 is
不告诉你它是否是特定类型 - 它告诉你它是否是特定类型或该类型的任何派生类型。
因此,如果你有两个类,Animal 和 Cat:Animal,而 felix 是一只猫,则
if (felix is Animal)
{
//returns true
}
if (felix.GetType() == typeof(Animal))
{
//does not
}
如果你不在意继承类,那么不用担心,像其他人提到的那样使用!(felix is Animal)
就可以了,没问题!(你可能没问题)
但是如果你确信felix是一个Animal,那么你需要问t.GetType()==typeof(TypeA)
。
如果你在if块内执行TypeA x = (TypeA)t;
操作,更好的方式是
TypeA x = t as TypeA
if(x != null)
{
...
}
我通常将空值检查和类型检查放在同一行:
if (t == null || !(t is TypeA)) {
...
}
if (t == null || t.GetType() != typeof(TypeA)) {
...
}
getType()
的示例:object obj = new object();
obj.GetType();
string s;
s.GetType();
List<string> StringList = new List<string>();
StringList.GetType();