要測試您的實例是否爲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");
請注意,如果該類是從該類的通用形式派生的,則這將不起作用。換句話說,'公共類Foo:MyGenericClass {}'不合格。 –
2010-11-05 04:27:25
@亞當,好點。你可以編寫代碼進一步測試。我會在如何做到這一點上添加*一個想法*。 – 2010-11-05 04:45:55