我有以下实用程序例程,用于确定一个类型是否派生自特定类型:
但我需要的是以下内容。
private static bool DerivesFrom(Type rType, Type rDerivedType)
{
while ((rType != null) && ((rType != rDerivedType)))
rType = rType.BaseType;
return (rType == rDerivedType);
}
< p >< em >(实际上我不知道是否有更方便的方法来测试导出...)
< p >问题在于我想确定一个类型是否从泛型类型派生,但是不指定泛型参数。
< p >例如,我可以编写:
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);
}
}
}