c# - 当 T 未知时,如何使用反射执行 List<object>.Cast<T>

标签 c# generics reflection casting

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

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

另一种选择是在您自己的类中编写一个通用方法来执行此操作,并通过反射调用 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 });
}

关于c# - 当 T 未知时,如何使用反射执行 List<object>.Cast<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1406345/

相关文章:

c# - 如何使用正文属性将附件插入 System.Net.Mail.mailMessage

algorithm - 通用排序函数接受 T,但要确保 T 是可比较的

scala - Scala 中的类型推断和类型界限

java - Method Reflect - 方法的调用顺序

java - 枚举的 values() 方法访问级别

c# - 如何重写 WPF DataGrid 行为以实现对外部应用程序的拖放操作?

c# - WPF - 从 UserControl 操作 VisualState

c# - 完全删除 "App.xaml"并创建自己的入口点,后果是什么?

java - 如何在java中调用带有嵌套泛型的构造函数

c# - 如何使用反射调用泛型方法?