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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With