How can I know the classes that extend my base class at runtime? [duplicate]

偶尔善良 提交于 2020-01-07 09:06:43

问题


During runtime, I would like to populate a drop down list with classes that have extended my base class. Currently I have an enum, and this is what I use to populate that list, but I want to add additional classes (and other people are adding classes) and do not want to have to maintain an enum for this purpose. I would like to add a new class and magically (reflection possibly) that class appears in the list without any addition code written for the drop down, or any additional enum added.

class Animal { ... }

enum AllAnimals { Cat, Dog, Pig };
class Cat : Animal {...}
class Dog : Animal {...}
class Pig : Animal {...}

Is there a way to accomplish this?


回答1:


Use reflection to get the loaded assemblies and then enumerate through all types that are a subclass of your base class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            var types = new List<Type>();

            foreach (var assembly in assemblies)
                types.AddRange(assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(Animal))));

            foreach (var item in types)
                Console.WriteLine(item.Name);
        }
    }

    class Animal { }

    enum AllAnimals { Cat, Dog, Pig };
    class Cat : Animal { }
    class Dog : Animal { }
    class Pig : Animal { }
}


来源:https://stackoverflow.com/questions/24999681/how-can-i-know-the-classes-that-extend-my-base-class-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!