【问题标题】:How can I perform a List<object>.Cast<T> using reflection when T is unknown当 T 未知时,如何使用反射执行 List<object>.Cast<T>
【发布时间】:2009-09-10 16:31:54
【问题描述】:

我已经尝试了好几个小时了,这就是我所能做到的

var castItems = typeof(Enumerable).GetMethod("Cast")
                  .MakeGenericMethod(new Type[] { targetType })
                  .Invoke(null, new object[] { items });

这让我回来了

System.Linq.Enumerable+d__aa`1[MyObjectType]

而我需要(对于我的 ViewData)作为通用列表,即

System.Collections.Generic.List`1[MyObjectType]

任何指针都会很棒

【问题讨论】:

    标签: c# generics reflection casting


    【解决方案1】:

    之后你只需要调用 ToList() 即可:

    static readonly MethodInfo CastMethod = typeof(Enumerable).GetMethod("Cast");
    static readonly MethodInfo ToListMethod = typeof(Enumerable).GetMethod("ToList");
    
    ...
    
    var castItems = CastMethod.MakeGenericMethod(new Type[] { targetType })
                              .Invoke(null, new object[] { items });
    var list = ToListMethod.MakeGenericMethod(new Type[] { targetType })
                              .Invoke(null, new object[] { castItems });
    

    另一种选择是在您自己的类中编写一个通用方法来执行此操作,并使用反射调用 that

    private static List<T> CastAndList(IEnumerable items)
    {
        return items.Cast<T>().ToList();
    }
    
    private static readonly MethodInfo CastAndListMethod = 
        typeof(YourType).GetMethod("CastAndList", 
                                   BindingFlags.Static | BindingFlags.NonPublic);
    
    public static object CastAndList(object items, Type targetType)
    {
        return CastAndListMethod.MakeGenericMethod(new[] { targetType })
                                .Invoke(null, new[] { items });
    }
    

    【讨论】:

    • 谢谢 完全忘记了(代码失明)谢谢。 [顺便说一句,您的方法中有一个错字,任何可能想要复制任何粘贴的人都应该说 var list =ToListMethod.MakeGen.....]
    • 太棒了。很难找到,但完全解决了我的问题。谢谢大家。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 2018-12-16
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多