C# 如何检查对象是否不是特定类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10549727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if an object is not of a particular type?
提问by Sachin Kainth
I want to check if an object is not of a particular type. I know how to check if something isof a particular type:
我想检查一个对象是否不是特定类型。我知道如何检查某物是否属于特定类型:
if (t is TypeA)
{
...
}
but
但
if (t isnt TypeA)
{
...
}
doesn't work.
不起作用。
采纳答案by ie.
C# is not quite natural language ;) Use this one
C# 不是很自然的语言 ;) 使用这个
if(!(t is TypeA))
{
...
}
回答by Tigran
回答by softveda
If you are doing a TypeA x = (TypeA)t;inside the if block then a better way is
如果你TypeA x = (TypeA)t;在 if 块里面做一个更好的方法是
TypeA x = t as TypeA
if(x != null)
{
...
}
This causes only one time type checking rather than twice.
这只会导致一次类型检查而不是两次。
回答by Ross
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)) {
...
}
回答by user2490832
Check below example for getType():
检查以下示例getType():
object obj = new object();
obj.GetType();
string s;
s.GetType();
List<string> StringList = new List<string>();
StringList.GetType();
回答by Paleta
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)))
{
...
}
回答by Peter Kay
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. isdoesn't tell you if it's a particular type - it tells you if it's a particular type or any descendant ofthat 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! (You're probably fine.)
如果对你来说不重要,继承的类也可以,那就不用管了,照!(felix is Animal)别人说的用就行了!(你可能没事。)
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).

