为实现接口的每个类获取一个实例
本文关键字:实例 一个 获取 实现 接口 | 更新日期: 2023-09-27 18:28:53
为了使用反射解决解决方案中的问题,我需要指定以下代码向用户显示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);
}
有可能得到一个物体吗?处理这样的问题最好的方法是什么?
只需使用Activator.CreateInstance
方法:
IConditions i = Activator.CreateInstance(type) as IConditions;
注意:如果type
没有无参数构造函数,此操作将失败。您可以使用带有参数的版本:
public static Object CreateInstance(Type type, params Object[] args)