将 List<Object> 动态转换为 List<Customer>
Dynamically convert List<Object> to List<Customer>
我有一个列表,只有在运行时通过反射才能找到对象的类型。但是当我尝试将列表分配给实际实体时,它会抛出错误 "object cannot be converted"。下面是代码,
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
,而是 Customer
的 List
。
所以你应该这样得到它的类型:
var listType = typeof(List<>).MakeGenericType(t);
但是您无法将您的对象转换为这个 listType
,您将得到一个 Exception
,List
没有实现 IConvertible
接口。
解决方案是:创建新列表并将所有数据复制到其中:
object data = Activator.CreateInstance(listType);
foreach (var o in obj)
{
listType.GetMethod("Add").Invoke(data, new []{o} );
}
我有一个列表,只有在运行时通过反射才能找到对象的类型。但是当我尝试将列表分配给实际实体时,它会抛出错误 "object cannot be converted"。下面是代码,
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
,而是 Customer
的 List
。
所以你应该这样得到它的类型:
var listType = typeof(List<>).MakeGenericType(t);
但是您无法将您的对象转换为这个 listType
,您将得到一个 Exception
,List
没有实现 IConvertible
接口。
解决方案是:创建新列表并将所有数据复制到其中:
object data = Activator.CreateInstance(listType);
foreach (var o in obj)
{
listType.GetMethod("Add").Invoke(data, new []{o} );
}