简体   繁体   中英

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

I have a generic as follows.

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

I simply want to invoke ToList() method on that object at runtime using reflection.

Can someone please help.

I have come so only far.

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

I get exception at the last line with message, Parameter count mismatch . I feel that the first two steps are ok, as I have checked the toListMethod.ToString() and constructedToList.ToString() . And they have given me the following output, which I feel is correct.

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])

Questions: 1. Am I right so far?

  1. What should be the parameter to MakeGenericMethod() method. In my case it is the Type of intance of the object of Type T at runtime.

  2. There seems to be some problem with the Invoke method call. Is passing null correct as second parameter? The first parameter should be an object of the type PaginatedList right?

My energy is out, so kindly help.

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

ToList is a static method on Enumerable that takes an IEnumerable<T> as it's only parameter:

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

Invoke takes the instance as the first parameter and the method parameters after that. For a static method you use null for the "instance" parameter.

So the proper syntax would be

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

o will then be an object of type List<T> (but you don't know kniw what T is at compile time, so you can't cast it).

List <T>具有一个采用IEnumerable <T>的构造函数(在ToList中被调用),因此您可以通过编写以下代码轻松完成此任务:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM