gpt4 book ai didi

c# - 将 List 动态转换为 List
转载 作者:太空宇宙 更新时间:2023-11-03 23:05:39 26 4
gpt4 key购买 nike

我有一个列表,只有在运行时通过反射才能找到对象的类型。但是当我尝试将列表分配给实际实体时,它会抛出错误,因为“无法转换对象”。下面是代码,

var obj = new List<Object>();
obj.Add(cust1);
obj.Add(Cust2);
Type newType = t.GetProperty("Customer").PropertyType// I will get type from property
var data= Convert.ChangeType(obj,newType); //This line throws error`

最佳答案

您的obj 对象不是Customer,它是CustomerList。所以你应该这样得到它的类型:

var listType = typeof(List<>).MakeGenericType(t);

但是你不能将你的对象转换成这个listType,你会得到一个Exception,那个List没有实现IConvertible 接口(interface)。

解决方案是:创建新列表并将所有数据复制到其中:

object data = Activator.CreateInstance(listType);
foreach (var o in obj)
{
listType.GetMethod("Add").Invoke(data, new []{o} );
}

关于c# - 将 List<Object> 动态转换为 List<Customer>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41291963/

26 4 0