gpt4 book ai didi

c# - 动态创建结构的List<>

转载 作者:行者123 更新时间:2023-12-01 19:40:50 24 4
gpt4 key购买 nike

在 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 接口(interface)访问它

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

关于c# - 动态创建结构的List<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1924733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com