List<> of dynamically created structure

2019-07-16 22:31发布

问题:

In C# I want to create a list based on a dynamic value type, e.g.:

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>();
}

This won't comple because List<> wants a staticly defined type name. Is there any way to work around this?

回答1:

You are going to have to use reflection to create the list:

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

IList list = Activator.CreateInstance(concreteType) as IList;


回答2:

You can create a strongly-typed list at runtime through reflection although you can only access it through the non-generic IList interface

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