簡體   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