问题
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