How to find all the types in an Assembly that Inherit from a Specific Type C#

前端 未结 4 1240
孤独总比滥情好
孤独总比滥情好 2020-12-02 11:58

How do you get a collection of all the types that inherit from a specific other type?

4条回答
  •  不思量自难忘°
    2020-12-02 12:21

    Something like:

    public IEnumerable FindDerivedTypes(Assembly assembly, Type baseType)
    {
        return assembly.GetTypes().Where(t => baseType.IsAssignableFrom(t));
    }
    

    If you need to handle generics, that gets somewhat trickier (e.g. passing in the open List<> type but expecting to get back a type which derived from List). Otherwise it's simple though :)

    If you want to exclude the type itself, you can do so easily enough:

    public IEnumerable FindDerivedTypes(Assembly assembly, Type baseType)
    {
        return assembly.GetTypes().Where(t => t != baseType && 
                                              baseType.IsAssignableFrom(t));
    }
    

    Note that this will also allow you to specify an interface and find all the types which implement it, rather than just working with classes as Type.IsSubclassOf does.

提交回复
热议问题