2010-11-05 92 views
3

說我有一個簡單的泛型類,如下所示如何測試某個類的實例是否是特定的泛型類型?

public class MyGenericClass<t> 
{ 
    public T {get;set;} 
} 

我怎麼能測試一個類的實例是這樣的MyGenericClass?例如,我想要做這樣的事情:

MyGenericClass x = new MyGenericClass<string>(); 
bool a = x is MyGenericClass; 
bool b = x.GetType() == typeof(MyGenericClass); 

然而,我不能只是參考MyGenericClass。 Visual Studio總是要我寫MyGenericClass<something>

回答

2

要測試您的實例是否爲MyGenericClass<T>類型,您可以編寫類似這樣的內容。

MyGenericClass<string> myClass = new MyGenericClass<string>(); 
bool b = myClass.GetType().GetGenericTypeDefinition() == typeof(MyGenericClass<>); 

如果你希望能夠來聲明對象MyGenericClass而不是MyGenericClass<string>,那就需要的MyGenericClass非通用基礎是繼承樹的一部分。但是在那個時候,你只能引用基礎上的屬性/方法,除非你後來轉換爲派生的泛型類型。不能省略時,直接聲明一個泛型實例的類型參數*

*您可以,當然,選擇使用類型推斷,寫

var myClass = new MyGenericClass<string>(); 

編輯:亞當 - 羅賓遜在一個好點評論,說你有class Foo : MyGenericClass<string>。上面的測試代碼不會將Foo的實例標識爲MyGenericClass<>,但您仍然可以編寫代碼來測試它。

Func<object, bool> isMyGenericClassInstance = obj => 
    { 
     if (obj == null) 
      return false; // otherwise will get NullReferenceException 

     Type t = obj.GetType().BaseType; 
     if (t != null) 
     { 
      if (t.IsGenericType) 
       return t.GetGenericTypeDefinition() == typeof(MyGenericClass<>); 
     } 

     return false; 
    }; 

bool willBeTrue = isMyGenericClassInstance(new Foo()); 
bool willBeFalse = isMyGenericClassInstance("foo"); 
+0

請注意,如果該類是從該類的通用形式派生的,則這將不起作用。換句話說,'公共類Foo:MyGenericClass {}'不合格。 – 2010-11-05 04:27:25

+0

@亞當,好點。你可以編寫代碼進一步測試。我會在如何做到這一點上添加*一個想法*。 – 2010-11-05 04:45:55

0
List<int> testInt = new List<int>(); 
List<string> testString = new List<string>(); 

if (testInt .GetType().Equals(testString.GetType())) 
Console.WriteLine("Y"); 
else Console.WriteLine("N"); 

它的 'N'

testInt.GetType().Equals(typeof(List<int>)) 
is true 

但如果ü只想類名

testInt.GetType().FullName 
0

你可以,如果需要的話,使通用類實現一些任意的(可能是空的)接口。測試某個對象是否爲通用泛型類將僅僅是測試它是否實現了該接口。不需要明確使用反射。

相關問題