在 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>();
}
这不会编译,因为 List 需要静态定义的类型名称。有什么办法可以解决这个问题吗?
您可以在运行时通过反射创建强类型列表,尽管您只能通过非泛型 IList 接口访问它
IList myTable = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(new[] { myType }));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)