微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 当T未知时,如何使用反射来执行List.Cast

我一直在尝试这么做几个小时,这是我所知道的
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]

任何指针都会很棒

解决方法

你只需要调用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 });

一个选择是在你自己的类中编写一个泛型方法来做这个,并用反射来调用它:

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 });
}

原文地址:https://www.jb51.cc/csharp/91942.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐