C# 列表<&燃气轮机;动态创建结构的设计

C# 列表<&燃气轮机;动态创建结构的设计,c#,generics,reflection,C#,Generics,Reflection,在C#中,我想创建一个基于动态值类型的列表,例如: void Function1() { TypeBuilder tb = .... // tb is a value type ... Type myType = tb.CreateType(); List<myType> myTable = new List<myType>(); } void Function2(Type myType) { List<myType> myTabl

在C#中,我想创建一个基于动态值类型的列表,例如:

void Function1() {

  TypeBuilder tb = ....   // tb is a value type
  ...
  Type myType = tb.CreateType();
  List<myType> myTable = new List<myType>();
}

void Function2(Type myType)
{
  List<myType> myTable = new List<myType>();
}
void Function1(){
TypeBuilder tb=..//tb是一种值类型
...
类型myType=tb.CreateType();
List myTable=新列表();
}
无效函数2(类型myType)
{
List myTable=新列表();
}

由于列表需要一个静态定义的类型名,因此此操作不会复杂。有办法解决这个问题吗?

您可以在运行时通过反射创建强类型列表,尽管您只能通过非通用IList接口访问它

IList myTable = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(new[] { myType }));
IList myTable=(IList)Activator.CreateInstance(typeof(List).MakeGenericType(new[]{myType}));

您必须使用反射来创建列表:

Type listType = typeof(List<>);
Type concreteType = listType.MakeGenericType(myType);

IList list = Activator.CreateInstance(concreteType) as IList;
Type listType=typeof(列表);
类型concreteType=listType.MakeGenericType(myType);
IList list=Activator.CreateInstance(concreteType)作为IList;

这需要使用System.Collections进行编译。这需要使用System.Collections进行编译。