查找所有派生类型的泛型类

wei*_*in8 20 c# reflection

我有一个泛型类和一个派生类如下.

public class GenericClass<T> { ... }

public class DerivedClass : GenericClass<SomeType> { ... }
Run Code Online (Sandbox Code Playgroud)

如何通过反射找到派生类?我在下面尝试了两种方法,但似乎没有用.

System.Reflection.Assembly.GetExecutingAssembly().GetTypes().Where(t => typeof(GenericClass<>).IsAssignableFrom(t));

System.Reflection.Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsSubclassOf(typeof(GenericClass<>));
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 39

var result = System.Reflection.Assembly.GetExecutingAssembly()
    .GetTypes()
    .Where(t => t.BaseType != null && t.BaseType.IsGenericType && 
                t.BaseType.GetGenericTypeDefinition() == typeof(GenericClass<>));
Run Code Online (Sandbox Code Playgroud)

  • 如果您的 GenericClass 采用多个类型参数,请为每个附加参数添加一个逗号 - `typeof(GenericClass&lt;,&gt;)` 、 `typeof(GenericClass&lt;,,&gt;)` 等等。 (2认同)

Pav*_*dov 9

它比这复杂一点.t.BaseType可以返回null(例如,当t是接口时).另请注意,Type.IsSubclassOf方法不适用于泛型类型!如果您正在处理泛型类型,则应使用GetTypeDefinition方法.我最近写了一篇关于如何获取类的所有派生类型的博客.这是一个适用于泛型的IsSubclass方法:

public static bool IsSubclassOf(Type type, Type baseType)
{
    if (type == null || baseType == null || type == baseType)
        return false;

    if (baseType.IsGenericType == false)
    {
        if (type.IsGenericType == false)
            return type.IsSubclassOf(baseType);
    }
    else
    {
        baseType = baseType.GetGenericTypeDefinition();
    }

    type = type.BaseType;
    Type objectType = typeof(object);
    while (type != objectType && type != null)
    {
        Type curentType = type.IsGenericType ?
            type.GetGenericTypeDefinition() : type;
        if (curentType == baseType)
            return true;

        type = type.BaseType;
     }

    return false;
}
Run Code Online (Sandbox Code Playgroud)