我有以下实用程序例程来确定类型是否派生自特定类型:
private static bool DerivesFrom(Type rType, Type rDerivedType)
{
while ((rType != null) && ((rType != rDerivedType)))
rType = rType.BaseType;
return (rType == rDerivedType);
}
(其实不知道有没有更方便的方法来测试推导...)
问题是我想确定一个类型是否派生自泛型类型,但没有指定泛型参数。
例如我可以写:
DerivesFrom(typeof(ClassA), typeof(MyGenericClass<ClassB>))
但我需要的是以下
DerivesFrom(typeof(ClassA), typeof(MyGenericClass))
我怎样才能实现它?
基于Darin Miritrov的示例,这是一个示例应用程序:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace ConsoleApplication1
{
public class MyGenericClass<T> { }
public class ClassB {}
public class ClassA : MyGenericClass<ClassB> { }
class Program
{
static void Main()
{
bool result = DerivesFrom(typeof(ClassA), typeof(MyGenericClass<>));
Console.WriteLine(result); // prints **false**
}
private static bool DerivesFrom(Type rType, Type rDerivedType)
{
return rType.IsSubclassOf(rDerivedType);
}
}
}