[英]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.