我有以下的例子类:反思 - 泛型列表调用方法,结果
public class MyClass<T>
{
public IList<T> GetAll()
{
return null; // of course, something more meaningfull happens here...
}
}
而且我想调用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);
这导致(上以上代码的最后一行):
无法在ContainsGenericParameters类型或方法上执行后期操作真正。
好的,第二次尝试:
MethodInfo getAllMethod = myClassType.GetMethod("GetAll", new Type[] {});
getAllMethod = getAllMethod.MakeGenericMethod(typeof(object));
object magicValue = getAllMethod.Invoke(myClassInstance, null);
这导致(在上述第二代码最后一行):
System.Collections.Generic.IList`1 [T] GETALL ()不是GenericMethodDefinition。 MakeGenericMethod只能在MethodBase.IsGenericMethodDefinition为true的方法上调用。
我在这做错了什么?
'baseRepo'在最后一行来自哪里?它不应该是'myClassInstance'吗? – 2012-01-27 15:51:20
您的示例代码必须在此行中有一个错误:MethodInfo getAllMethod = myClassInstance.GetMethod(“GetAll”,new Type [] {}); – usr 2012-01-27 15:52:07
是的,OP可能使用了''myClassType''而不是''构造''。我纠正之后,它为我工作。 – 2012-01-27 15:53:29