我有一个泛型如下。
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. 目前为止我说的对吗?
MakeGenericMethod()
方法的参数应该是什么。在我的例子中,它是运行时类型 T 对象的实例类型。Invoke 方法调用似乎有问题。作为第二个参数传递 null 是否正确?第一个参数应该是 PaginatedList 类型的对象吧?
我的能量耗尽了,请帮忙。
最佳答案
The first parameter [to
Invoke
] should be an object of the type PaginatedList right?
ToList
是 Enumerable
上的静态方法这需要 IEnumerable<T>
因为它只是参数:
public static List<TSource> ToList<TSource>(
this IEnumerable<TSource> source
)
Invoke
将实例作为第一个参数,然后是方法参数。对于静态方法,您使用 null
对于“实例”参数。
所以正确的语法应该是
object o = constructedToList.Invoke(null, new object[] {paginatedListObject});
o
然后将是 List<T>
类型的对象(但是你不知道 T
在编译时是什么,所以你不能转换它)。
关于c# - 在 C# 中使用反射在运行时调用 ToList() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33155101/