2014-11-02 133 views
1

爲了解決我在使用反射的解決方案中遇到的問題,我需要指定以下代碼以向用戶顯示一個CheckedListBox,它顯示了它們具有的條件列表選擇,並根據他們的選擇修改應用程序中的某種行爲。 在這個時候,我沒有問題得到繼承類的字符串名稱感謝this後,但我不知道如何獲得每個實例。獲取實現接口的每個類的實例

 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); 
     } 

可能得到一個對象嗎?處理這樣的問題的更好的方法是什麼?

回答

1

只需使用Activator.CreateInstance方法:

IConditions i = Activator.CreateInstance(type) as IConditions; 

注:這將失敗,如果type沒有參數的構造函數。您可以使用帶有參數的版本:

public static Object CreateInstance(Type type, params Object[] args) 
+0

優秀的Konrad!這是我需要的!我的情況構造函數不是一個問題,但是是一個有效的聲音。 – 2014-11-02 19:59:06