Generating a list of child classes with reflection in .NET 3.5

后端 未结 3 1656
既然无缘
既然无缘 2021-01-21 07:05

At runtime, I would like to specify a parent class, and then the program would generate a list of all children classes (of however many generations). For example, if I had

3条回答
  •  一向
    一向 (楼主)
    2021-01-21 07:30

    This is what I use to find all children of some class (can be also abstract class) in selected assembly:

    public class InheritedFinder
    {
        public static Type[] FindInheritedTypes(
            Type parentType, Assembly assembly)
        {
            Type[] allTypes = assembly.GetTypes();
            ArrayList avTypesAL = new ArrayList();
    
            return allTypes.Where(
                t => parentType.IsAssignableFrom(t) && t != parentType).ToArray();
        }
    }
    

    Simply call by

    var availableTypes = InheritedFinder.FindInheritedTypes(
            typeof(YourBaseClass),
            System.Reflection.Assembly.GetExecutingAssembly());
    

    This will give you list of available children of YourBaseClass. Nice thing about it - it'll find also children of children, so you can use multi-level abstract classes. If you need to create instances of every child, easy:

    var availableTypes= InheritedFinder.FindInheritedTypes(
        typeof(Shape), System.Reflection.Assembly.GetExecutingAssembly());
    foreach (var t in availableTypes)
    {
        try
        {
            YourBaseClass nInstance = (YourBaseClass)Activator.CreateInstance(t);
            //nInstance is now real instance of some children
        }
        catch (Exception e)
        {
            //recommended to keep here - it'll catch exception in case some class is abstract (=can't create its instance)
        }
    }
    

提交回复
热议问题