I have the following example-class:
public class MyClass<T>
{
public IList<T> GetAll()
{
return null; // of course, something more meaningfull happens here...
}
}
And I would like to invoke GetAll
with reflection:
Type myClassType = typeof(MyClass<>);
Type[] typeArgs = { typeof(object) };
Type constructed = myClassType.MakeGenericType(typeArgs);
var myClassInstance = Activator.CreateInstance(constructed);
MethodInfo getAllMethod = myClassType.GetMethod("GetAll", new Type[] {});
object magicValue = getAllMethod.Invoke(myClassInstance, null);
This results in (on last line of above code):
Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.
Okay, second try:
MethodInfo getAllMethod = myClassType.GetMethod("GetAll", new Type[] {});
getAllMethod = getAllMethod.MakeGenericMethod(typeof(object));
object magicValue = getAllMethod.Invoke(myClassInstance, null);
This results in (on second last line of above code):
System.Collections.Generic.IList`1[T] GetAll() is not a GenericMethodDefinition. MakeGenericMethod may only be called on a method for which MethodBase.IsGenericMethodDefinition is true.
What am I doing wrong here?