3

I've looked at other questions like this but am having no luck. I feel like I'm dancing around the answer.

After using reflection to call MethodInfo myMethod = MakeGenericMethod(Type.GetType(MyClass)) I have a MethodInfo object that looks like this in the debugger:

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

...and I try to call it like so using 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});

...but when I do this I get a parameter count mismatch, and I'm scratching my head as to why.

Is it because it's a generic method, possibly? Or perhaps the fact that Count is an extension method on connection?

For reference, a non-reflective, straighforward way of calling my method would be something like int count = connection.Count<MyRow>(new Criteria("some info here"));

Community
  • 1
  • 1
jkj2000
  • 1,563
  • 4
  • 19
  • 26

2 Answers2

6

That method is an extension method, so it isn't part of the class. The first parameter of Invoke should be null (it can even be non-null but it will be ignored)

int count = (int)myMethod.Invoke(null, new object [] { connection, myCriteria });
xanatos
  • 109,618
  • 12
  • 197
  • 280
  • Thank you very much, your suggestion worked great. The extension method bit played tricks on my eyes. – jkj2000 Mar 27 '17 at 06:35
1

As you said, the method info looks like this:

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

It returns an int and it accepts two parameters IDbConnection and ICriteria.

According to the docs, the second parameter of MethodInfo.Invoke is the parameters you pass to this method:

An argument list for the invoked method or constructor. This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked. If there are no parameters, parameters should be null.

The method info needs 2 parameters but you only gave it one. Exception!

"But when I call the method I need to say connection.Count(someCriteria) instead of Count(connection, someCriteria)!"

The only possibility is that Count is an extension method. Extension method seems like they can be called on an object. But as you may know, they are just syntactic sugar. They are just plain old static methods in essence. When doing reflection, you need to ignore the syntactic sugar because reflection does not care about those.

Sweeper
  • 213,210
  • 22
  • 193
  • 313