[英]How to check if an object is not of a particular type?
I want to check if an object is not of a particular type.我想检查一个对象是否不是特定类型。 I know how to check if something is of a particular type:
我知道如何检查某物是否属于特定类型:
if (t is TypeA)
{
...
}
but但
if (t isnt TypeA)
{
...
}
doesn't work.不起作用。
UPDATE 2020-10-30:更新 2020-10-30:
Times are changing.时代在变。 Starting from C# 9.0 you can use more natural way of checking it:
从 C# 9.0 开始,您可以使用更自然的检查方式:
if(t is not TypeA) { ... }
ORIGINAL ANSWER:原始答案:
C# is not quite natural language ;) Use this one C# 不是很自然的语言 ;) 使用这个
if(!(t is TypeA))
{
...
}
If you are doing a TypeA x = (TypeA)t;
如果你在做一个
TypeA x = (TypeA)t;
inside the if block then a better way is在 if 块中,更好的方法是
TypeA x = t as TypeA
if(x != null)
{
...
}
This causes only one time type checking rather than twice.这只会导致一次类型检查而不是两次。
Extensions methods to the rescue!!扩展方法来救援!!
public static class ObjectExtensions
{
public static bool Isnt(this object source, Type targetType)
{
return source.GetType() != targetType;
}
}
Usage用法
if (t.Isnt(typeof(TypeA)))
{
...
}
Short answer: you may want to use:简短回答:您可能想使用:
if (t.GetType()==typeof(TypeA))
{
...
}
if (t.GetType()!=typeof(TypeA))
{
...
}
Long answer:长答案:
So.所以。 Be aware that you're asking if it's a particular type.
请注意,您是在询问它是否是特定类型。
is
doesn't tell you if it's a particular type - it tells you if it's a particular type or any descendant of that type. is
不会告诉您它是否是特定类型 - 它会告诉您它是特定类型还是该类型的任何后代。
So if you have two classes, Animal, and Cat : Animal, and felix is a cat, then所以如果你有两个类,Animal 和 Cat:Animal,而 felix 是一只猫,那么
if (felix is Animal)
{
//returns true
}
if (felix.GetType() == typeof(Animal))
{
//does not
}
If it's not important to you, inherited classes are okay, then don't worry about it, use !(felix is Animal)
as others mentioned, and you're fine!如果这对你不重要,继承类也可以,那么不要担心,使用
!(felix is Animal)
就像其他人提到的那样,你很好! (You're probably fine.) (你可能没事。)
But if you need to be sure felix is specifically an Animal, then you need to ask if t.GetType()==typeof(TypeA)
.但是,如果您需要确定 felix 是专门的 Animal,那么您需要询问是否
t.GetType()==typeof(TypeA)
。
I usually stick the null and type checking all in one line:我通常将空值和类型检查全部放在一行中:
if (t == null || !(t is TypeA)) {
...
}
If TypeA is a struct, you'll need to handle it slightly differently again:如果 TypeA 是一个结构体,您需要再次以稍微不同的方式处理它:
if (t == null || t.GetType() != typeof(TypeA)) {
...
}
Check below example for getType()
:检查以下
getType()
示例:
object obj = new object();
obj.GetType();
string s;
s.GetType();
List<string> StringList = new List<string>();
StringList.GetType();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.