要测试您的实例是否为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