繁体   English   中英

为实现接口的每个类获取一个实例

[英]Get an instance for each class that implements an Interface

为了解决我在使用反射的解决方案中遇到的问题,我需要指定以下代码来向用户显示一个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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM