I have the following example class:
public class MyClass<T> { public IList<T> GetAll() { return null;
And I would like to call 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);
As a result (in the last line above the code):
Limited bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.
Ok, try again:
MethodInfo getAllMethod = myClassType.GetMethod("GetAll", new Type[] {}); getAllMethod = getAllMethod.MakeGenericMethod(typeof(object)); object magicValue = getAllMethod.Invoke(myClassInstance, null);
As a result (on the second last line above the code):
System.Collections.Generic.IList`1 [T] GetAll () is not a GenericMethodDefinition. MakeGenericMethod can only be called for a method that has the MethodBase.IsGenericMethodDefinition property set.
What am I doing wrong here?
source share