C# 如何使用类型列表作为泛型参数?

C# 如何使用类型列表作为泛型参数?,c#,list,generics,C#,List,Generics,我有许多类型都实现了一个简单的接口 我希望能够得到一个类型列表,然后在通用方法中使用它们 ForEach(var type in TypesThatImplement<Ifoo>){ DoThing.Doit<type>(); } ForEach(typesthateimplement中的变量类型){ DoThing.Doit(); } 而不必维护一份 DoThing.Doit<TypeA>(); DoThing.Doit<TypeB

我有许多类型都实现了一个简单的接口

我希望能够得到一个类型列表,然后在通用方法中使用它们

ForEach(var type in TypesThatImplement<Ifoo>){
    DoThing.Doit<type>();    
}
ForEach(typesthateimplement中的变量类型){
DoThing.Doit();
}
而不必维护一份

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

我真的看不出你这样做的实际原因(可能是更大问题的一小部分?),但这是可能的(见下文)。如果您有更具体的问题,可以尝试更新您的问题

        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 DoThing=new DoThing();
//循环使用IFoo类型
foreach(AppDomain.CurrentDomain.GetAssemblies()中的变量类型。SelectMany(s=>s.GetTypes())。其中(p=>typeof(IFoo)。IsAssignableFrom(p)和&p.IsClass))
{
//使用反射调用DoThing.Doit方法
MethodInfo method=typeof(DoThing).GetMethod(“Doit”);
MethodInfo generic=method.MakeGenericMethod(类型);
generic.Invoke(doThing,null);
}
注意,上面的代码假定圆点是定义的:

public class DoThing
{
    public void Doit<T>() where T : IFoo
    {
    }
}
公共类DoThing
{
public void Doit(),其中T:IFoo
{
}
}

这样做有什么问题?你试过什么?你可以看一看。所有这些类型都在同一个程序集中吗?如何获得所有的实现类型?你的问题太宽泛了。谢谢。需要“完成”的类型列表很长,并且将更长。如果我不必记得在创建它们时将它们添加到列表中,那么这对我来说是一件好事。