反射:作为结果使用通用列表调用方法

sl3*_*dg3 4 c# generics reflection

我有以下示例类:

public class MyClass<T>
{
    public IList<T> GetAll()
    {
        return null; // of course, something more meaningfull happens here...
    }
}
Run Code Online (Sandbox Code Playgroud)

我想GetAll用反思来调用:

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);
Run Code Online (Sandbox Code Playgroud)

这导致(在上面的代码的最后一行):

无法对ContainsGenericParameters为true的类型或方法执行后期绑定操作.

好的,第二次尝试:

MethodInfo getAllMethod = myClassType.GetMethod("GetAll", new Type[] {});
getAllMethod = getAllMethod.MakeGenericMethod(typeof(object));
object magicValue = getAllMethod.Invoke(myClassInstance, null);
Run Code Online (Sandbox Code Playgroud)

这导致(在上面代码的倒数第二行):

System.Collections.Generic.IList`1 [T] GetAll()不是GenericMethodDefinition.MakeGenericMethod只能在MethodBase.IsGenericMethodDefinition为true的方法上调用.

我在这做错了什么?

Pet*_*nks 6

我试过这个并且它有效:

// Create generic type
Type myClassType = typeof(MyClass<>);
Type[] typeArgs = { typeof(object) };   
Type constructed = myClassType.MakeGenericType(typeArgs);

// Create instance of generic type
var myClassInstance = Activator.CreateInstance(constructed);    

// Find GetAll() method and invoke
MethodInfo getAllMethod = constructed.GetMethod("GetAll");
object result = getAllMethod.Invoke(myClassInstance, null); 
Run Code Online (Sandbox Code Playgroud)