I created a generic function, as shown below (just a proof), which will take the List<T> collection and cancel it, returning a new List<T> .
public static List<T> ReverseList<T>(List<T> sourceList) { T[] outputArray = new T[sourceList.Count]; sourceList.CopyTo(outputArray); return outputArray.Reverse().ToList(); }
The purpose of the proof is that I only know that T at runtime. Therefore, I use reflection to call the above method as follows:
List<int> myList = new List<int>() { 1, 2, 3, 4, 5 }; // As an example, but could be any type for T MethodInfo myMethod = this.GetType().GetMethod("ReverseList"); MethodInfo resultMethod = myMethod.MakeGenericMethod(new Type[] { typeof(int) }); object result = resultMethod.Invoke(null, new object[] { myList });
There are two problems here:
- In the second line, instead of supplying
typeof(int) , I would like to ask somdign akin to myList.GetType().GetGenericArguments()[0].GetType() to make things more flexible, because I don't know T until time execution. This causes a runtime error when Invoke works as follows: "An object of type" System.Collections.Generic.List'1 [System.Int32] "cannot be converted to a type of" System.Collections.Generic.List'1 [System. RuntimeType]. " - The result of the
Invoke() method returns an object. When debugging, I see that the object is of type List, but trying to use it tells me that I have an invalid cast. I assume that I need to use reflection to give the result to the correct type (i.e., in this example, the equivalent (result as List<int> ).
Does anyone have pointers that could help me resolve this? Sorry, if this is not cleared, I may possibly provide more detailed information if asked.
TIA
source share