在 C# 中使用反射在运行时调用 ToList() 方法

Invoke ToList() method using reflection at runtime in C#

我有一个泛型如下

public class PaginatedList<T> : List<T>
{...}

我只想在运行时使用反射对该对象调用 ToList() 方法。

有人可以帮忙吗。

我只到此为止了

MethodInfo toListMethod = typeof(Enumerable).GetMethod("ToList");
var constructedToList = toListMethod.MakeGenericMethod(TypeObjectOfT);
constructedToList.Invoke(paginatedListObject, null);

我在消息的最后一行出现异常参数计数不匹配toListMethod.ToString()constructedToList.ToString()我都检查过了,感觉前两步没问题。他们给了我以下输出,我觉得是正确的。

System.Collections.Generic.List`1[TSource] ToList[TSource](System.Collections.Generic.IEnumerable`1[TSource])
System.Collections.Generic.List`1[AvbhHis.BL.Entities.PatientCategory] ToList[PatientCategory](System.Collections.Generic.IEnumerable`1[AvbhHis.BL.Entities.PatientCategory])

问题: 1. 到目前为止我说的对吗?

  1. MakeGenericMethod() 方法的参数应该是什么。在我的例子中,它是运行时类型 T 对象的实例类型。

  2. Invoke 方法调用似乎有问题。作为第二个参数传递 null 是否正确?第一个参数应该是 PaginatedList 类型的对象吧?

我的能量耗尽了,请帮助。

The first parameter [to Invoke] should be an object of the type PaginatedList right?

ToListEnumerable 上的静态方法,它采用 IEnumerable<T> 作为唯一参数:

public static List<TSource> ToList<TSource>(
    this IEnumerable<TSource> source
)

Invoke 实例 作为第一个参数,然后是 方法参数 。对于静态方法,您使用 null 作为 "instance" 参数。

所以正确的语法是

object o = constructedToList.Invoke(null, new object[] {paginatedListObject});

o 将成为 List<T> 类型的对象(但你不知道 T 在编译时是什么,所以你不能转换它)。

List 有一个采用 IEnumerable 的构造函数(在 ToList 中调用),因此您可以通过编写以下内容来简单地完成此任务:

    var resul = Activator.CreateInstance(typeof(List<>).MakeGenericType(TypeObjectOfT), paginatedListObject);