![](/img/trans.png)
[英]How to check for object of particular type in a HashSet in windows 8?
[英]How to check if an object is not of a particular type?
我想检查一个对象是否不是特定类型。 我知道如何检查某物是否属于特定类型:
if (t is TypeA)
{
...
}
但
if (t isnt TypeA)
{
...
}
不起作用。
更新 2020-10-30:
时代在变。 从 C# 9.0 开始,您可以使用更自然的检查方式:
if(t is not TypeA) { ... }
原始答案:
C# 不是很自然的语言 ;) 使用这个
if(!(t is TypeA))
{
...
}
如果你在做一个TypeA x = (TypeA)t;
在 if 块中,更好的方法是
TypeA x = t as TypeA
if(x != null)
{
...
}
这只会导致一次类型检查而不是两次。
扩展方法来救援!!
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 (t == null || !(t is TypeA)) {
...
}
如果 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.