为了解决我在使用反射的解决方案中遇到的问题,我需要指定以下代码来向用户显示一个 CheckedListBox,它公开了他们必须选择的条件列表,并根据他们的选择修改特定行为在应用程序中。目前,由于这篇文章,我没有问题获取继承类的字符串名称,但我不知道如何获取每个类的实例。
DataTable table = new DataTable();
table.Columns.Add("Intance", typeof(IConditions)); //INSTANCE of the inherited class
table.Columns.Add("Description", typeof(string)); //name of the inherited class
//list of all types that implement IConditions interface
var interfaceName = typeof(IConditions);
List<Type> inheritedTypes = (AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => interfaceName.IsAssignableFrom(p) && p != interfaceName)).ToList();
foreach (Type type in inheritedTypes)
{
IConditions i; //here is where I don't know how to get the instance of the Type indicated by 'type' variable
//I.E: IConditions I = new ConditionOlderThan20(); where 'ConditionOlderThan20' is a class which implements IConditions interface
table.Rows.Add(i, type.Name);
}
有可能得到一个对象吗?处理此类问题的更好方法是什么?