转换列表<对象>使用System.Type对象 [英] Converting List<Object> using a System.Type object

查看:62
本文介绍了转换列表<对象>使用System.Type对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经使用反射检索了System.Type对象,并希望使用该类型将List<Object>转换为该类型的另一个List.

Let's say I have retrieved a System.Type object using reflection and want to use that type to convert a List<Object> into another List of that type.

如果我尝试:

Type type = GetTypeUsingReflection();
var myNewList = listObject.ConvertAll(x => Convert.ChangeType(x, type)); 

由于对象未实现IConvertible接口,因此出现异常.是否有解决此问题的方法或解决此问题的另一种方法?

I get an exception since the object does not implement the IConvertible interface. Is there a way around this or another way to approach this problem?

推荐答案

Type type = typeof(int); // could as well be obtained by Reflection

var objList = new List<object> { 1, 2, 3 };
var intList = (IList) Activator.CreateInstance(
    typeof(List<>).MakeGenericType(type)
    );

foreach (var item in objList)
    intList.Add(item);

// System.Collections.Generic.List`1[[System.Int32, ...]]
Console.WriteLine(intList.GetType().FullName);

但是为什么在地球上需要它?

But why on Earth would you need it?

这篇关于转换列表&lt;对象&gt;使用System.Type对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆