如何将类型列表输入到泛型类

本文关键字:泛型类 输入 类型 列表 | 更新日期: 2023-09-27 18:36:57

我的泛型类看起来像这样:

public interface IFoo<T> where T : class
{
    IList<T> GetFoo();
}
public class Foo<T> : IFoo<T> where T : class
{
    public IList<T> GetFoo()
    {
       //return something in here
    }
}

我想使用程序集类型集合中的该类,如下所示:

public class Bar
{
    public IList<string> GetTheFoo()
    {
        IList<Type> theClass = Assembly.GetExecutingAssembly().GetTypes()
        .Where(t => t.IsClass).ToList();
        var theList = new List<string>();
        foreach (Type theType in theClass)
        {
            //not working...
            theList.Add(new Foo<theType>().GetFoo() );
        }
    }
}

但编译器不能接受列表中的类型。如何解决这个问题?

如何将类型列表输入到泛型类<T>中

您可以使用

Type.MakeGenericType动态创建所需的类型:

 var item = typeof(Foo<>).MakeGenericType(theType);

由于这些项目都不同,因此您只能将它们存储在List<object>中。