我有一个如下的通用类。
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 类型的对象才对吧?
我的精力已经耗尽,请帮忙。
Enumerable
是一个包含IEnumerable<T>
扩展方法的类。此外,msdn说_Enumerable确实有ToList()_。 - GrundyToList
的方法? - D StanleyEnumerable
上的ToList
。 - D Stanley