我如何知道在运行时扩展我的基类的类? [英] How can I know the classes that extend my base class at runtime?
问题描述
在 运行时 期间,我想使用扩展我的基类的类填充一个下拉列表。目前我有一个枚举,这是我用来填充该列表,但是我想添加额外的类(而其他人正在添加类),并且不希望为此目的维护一个枚举。我想添加一个新的类和魔术(反思可能)该类出现在列表中,没有添加代码为下拉列表写入,或添加任何其他枚举。
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 {...}
有没有办法完成这个?
推荐答案
使用反射来获取加载的程序集,然后通过作为基类子类的所有类型枚举。
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 { }
}
这篇关于我如何知道在运行时扩展我的基类的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!