【问题标题】:How can I use a list of types as a generic argument? [closed]如何使用类型列表作为通用参数? [关闭]
【发布时间】:2017-09-07 05:18:41
【问题描述】:

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

我希望能够获取类型列表,然后在通用方法中使用它们

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

而不是必须维护一个列表

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

【问题讨论】:

  • 这样做有什么问题?你试过什么?你可以看看stackoverflow.com/questions/4738280/…。所有这些类型都在同一个程序集中吗?你如何获得所有的实现类型?你的问题太笼统了。

标签: c# list generics


【解决方案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
    {
    }
}

【讨论】:

  • 谢谢。需要“完成”的类型列表很长,而且会更长。如果我不必记住在创建它们时将它们添加到列表中,那对我来说是件好事。
猜你喜欢
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
  • 2017-10-22
  • 2014-08-08
  • 2020-10-07
  • 2021-07-01
  • 2021-04-24
  • 1970-01-01
相关资源
最近更新 更多