加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:21:43 所属栏目:百科 来源:网络整理
导读:我一直在尝试这么做几个小时,这是我所知道的 var castItems = typeof(Enumerable).GetMethod("Cast") .MakeGenericMethod(new Type[] { targetType }) .Invoke(null,new object[] { items }); 这会让我回来 System.Linq.Enumerable+d__aa`1[MyObjectType] 而
我一直在尝试这么做几个小时,这是我所知道的
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 });
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读