我看过其他问题,例如this,但没有运气。我觉得我在围绕答案跳舞。

使用反射调用MethodInfo myMethod = MakeGenericMethod(Type.GetType(MyClass))后,我在调试器中有了一个MethodInfo对象,如下所示:

myMethod --> Int32 Count[MyClass](System.Data.IDbConnection, ICriteria)


...并且我尝试使用Invoke这样称呼它:

ICriteria myCriteria = new Criteria("some info here");

 //'connection' is an object of type System.Data.IDBConnection

int count = (int)myMethod.Invoke(connection, new object [] {myCriteria});


...但是当我这样做时,我得到了一个参数计数不匹配的信息,而我却为之困惑。

是否因为可能是通用方法?还是Countconnection的扩展方法的事实?

作为参考,调用我的方法的一种非反射,直观的方式类似于int count = connection.Count<MyRow>(new Criteria("some info here"));

最佳答案

该方法是扩展方法,因此它不是类的一部分。 Invoke的第一个参数应为null(甚至可以为非null,但将被忽略)

int count = (int)myMethod.Invoke(null, new object [] { connection, myCriteria });

10-06 13:06
查看更多