Bharani
Bharani

Reputation: 107

MethodInfo invoke for Overloaded methods in C#

I am using MethodInfo to invoke a overloaded method which is throwing me an exception TargetParameterCount mismatch and below is my code

public class Device
{
    public bool Send(byte[] d, int l, int t)
    {
        return this.Send(d, 0, l, t);
    }
 public bool Send(byte[] d, int l, int t,int t)
    {
        return true;
    }
}

And i someother class i am calling these functions.

public class dw
{
public bool BasicFileDownload(Device device)

{
Type devType = device.GetType();
byte [] dbuf = readbuff(); 
MethodInfo methodSend = deviceType.GetMethods().Where(m => m.Name =="Send").Last();
object invokeSend = methodOpen.Invoke(device, new object[] {dbuf,0,10,100 });
}
}

Now i am trying to invoke Send with 4 Parameters but it is throwing error.

System.Reflection.TargetParameterCountException: Parameter count mismatch. at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) at Download.BasicDownload.BasicFileDownload(Device device) in e:\sample\BDw.cs:line 146

Upvotes: 4

Views: 2364

Answers (3)

Seth Meyer
Seth Meyer

Reputation: 1

You should actually call the GetParameters method on the methodInfo. That will give you the correct parameters to have for the method

ParameterInfo[] Meth_Params = methodOpen.GetParameters(); dynamic[] inputparams = new dynamic[Meth_Params.Length]; inputparams[0] = first parameter;

and so on...

then assign the parameter array to the invoke object invokeSend = methodOpen.Invoke(device, inputparams);

Upvotes: 0

You can get the correct Send method directly by its signature.

var signature = new[] {typeof (byte[]), typeof (int), typeof (int), typeof (int)};
MethodInfo methodSend = deviceType.GetMethod("Send", signature);

This is more efficient than using Reflection to get all the type's methods and then filtering them afterwards.

Your code doesn't work because the order of methods returned by Reflection is not necessarily the same order that you declare them in code.

Upvotes: 4

Eser
Eser

Reputation: 12546

You can also check the parameters count..

MethodInfo methodSend = deviceType.GetMethods()
                        .Where(m => m.Name == "Send" && m.GetParameters().Length==4).First();

If your case gets more complicated than this, you may also need to check the parameter types...

Upvotes: 2

Related Questions