Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MethodInfo invoke for Overloaded methods in C#

Tags:

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

like image 812
Bharani Avatar asked Oct 25 '25 00:10

Bharani


1 Answers

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.

like image 55
Joel V. Earnest-DeYoung Avatar answered Oct 26 '25 13:10

Joel V. Earnest-DeYoung