2017-09-06 20 views
-1

我有許多類型都實現了一個簡單的界面。如何使用類型列表作爲一般參數?

我希望能夠得到的類型的列表,然後在一個通用的方法使用它們

ForEach(var type in TypesThatImplement<Ifoo>){ 
    DoThing.Doit<type>();  
} 

不是寧願保持

DoThing.Doit<TypeA>(); 
DoThing.Doit<TypeB>(); 
DoThing.Doit<TypeC>(); 
+1

什麼是這樣做的問題了嗎?你有什麼嘗試?你可以看看https://stackoverflow.com/questions/4738280/use-reflection-to-call-generic-method-on-object-instance-with-signature-someobj。所有這些類型都在同一個程序集中?你如何獲得所有的實現類型?你的問題太廣泛了。 – HimBromBeere

回答

1

我不列表你真的可以看到你這樣做的一個實際原因(也許是一個更大問題的一小部分?),但它是可能的(見下文)。如果你有更具體的問題,也許嘗試更新你的問題。

 DoThing doThing = new DoThing(); 

     //loop through types which are IFoo 
     foreach (var type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes()).Where(p => typeof(IFoo).IsAssignableFrom(p) && p.IsClass)) 
     { 
      //call DoThing.Doit<t> method using reflection 
      MethodInfo method = typeof(DoThing).GetMethod("Doit"); 
      MethodInfo generic = method.MakeGenericMethod(type); 
      generic.Invoke(doThing, null); 
     } 

注意,上面的代碼假定DoThing定義:

public class DoThing 
{ 
    public void Doit<T>() where T : IFoo 
    { 
    } 
} 
+0

謝謝。需要'完成'的類型列表很長,並且會更長。如果我不必在創建時將它們添加到列表中,那對我來說這是一件好事。 – Loofer

相關問題