【问题标题】:Converting List<Object> using a System.Type object使用 System.Type 对象转换 List<Object>
【发布时间】:2010-09-29 16:15:43
【问题描述】:

假设我使用反射检索了一个System.Type 对象,并希望使用该类型将List&lt;Object&gt; 转换为该类型的另一个列表。

如果我尝试:

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

我得到一个异常,因为该对象没有实现IConvertible 接口。有没有办法解决这个问题或其他方法来解决这个问题?

【问题讨论】:

  • 新旧类型有什么关系?一个如何转换为另一个?

标签: .net list reflection


【解决方案1】:

您提出的解决方案实际上不会起作用 - 它只会创建另一个List&lt;Object&gt;,因为ChangeType 的返回类型是Object。

假设您只想投射,您可以执行以下操作:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

class Test
{
    private static List<T> ConvertListImpl<T>(List<object> list)
    {
        return list.ConvertAll(x => (T) x);
    }

    // Replace "Test" with the name of the type containing this method
    private static MethodInfo methodDefinition = typeof(Test).GetMethod
        ("ConvertListImpl", BindingFlags.Static | BindingFlags.NonPublic);

    public static IEnumerable ConvertList(List<object> list, Type type)
    {
        MethodInfo method = methodDefinition.MakeGenericMethod(type);
        return (IEnumerable) method.Invoke(null, new object[] { list });
    }

    static void Main()
    {
        List<object> objects = new List<object> { "Hello", "there" };
        List<string> strings = (List<string>) ConvertList(objects,
                                                          typeof(string));

        foreach (string x in strings)
        {
            Console.WriteLine(x);
        }
    }
}

【讨论】:

    【解决方案2】:
    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);
    

    但是你到底为什么需要它呢?

    【讨论】:

    • 谢谢,就像一个魅力!原因是这样的:假设出于依赖注入的目的,我通过反射可以找到实现某个接口的类,该类的方法采用 List 作为参数。在运行时我不知道 T 是什么,但我可以检索类型。不是最好的解释,但希望是一个提示。
    • 你看,我问的原因是因为我最近在处理 NHibenate 对象和同步不同数据库的层 - 而且,随着它变得越来越复杂,我们需要保持事情很抽象,我开始像这个代码示例一样引入越来越多的反射疯狂。然后,在某一时刻,我只是删除了泛型和类型安全(无论如何这都没用,因为这些值是通过反射获得和设置的),并且使所有内容都无类型和简单结果是最好的解决方案,后来很难高估.让事情尽可能简单。
    【解决方案3】:

    当在设计时类型未知时,强制转换几乎没有用处。将新的对象列表转换为新类型后,您将如何使用新类型?您不能调用该类型公开的方法(不使用更多反射)

    【讨论】:

      【解决方案4】:

      类型系统无法从存储类型 T 的类型变量转换为类型 T 的泛型参数。

      从技术上讲,您可以创建正确类型的通用列表(使用反射),但类型信息在编译时不可用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-04
        • 2021-09-27
        • 1970-01-01
        • 1970-01-01
        • 2019-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多