0

look this code please :

// this method have a optional parameter
public static void Foo(int a = 3) { }

var del = new Action<int>(Foo);

// pass Type.Missing
del.DynamicInvoke(Type.Missing);

// or
del.DynamicInvoke(new object[] { Type.Missing });

it will get exception System.ArgumentException:

System.ArgumentException: Missing parameter does not have a default value.
Parameter name: parameters
   at System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig)
   at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at xxx.btnSetting_Click(Object sender, EventArgs e) in xxx\FmMain.cs:line 106

please help.

ahdung
  • 350
  • 3
  • 13
  • Possible duplicate of [Using C# delegates with methods with optional parameters](https://stackoverflow.com/questions/5729154/using-c-sharp-delegates-with-methods-with-optional-parameters) – thehennyy Jul 30 '19 at 08:41
  • @thehennyyHmmm, not really, that question is about match delegate and method, this question is about executing problem. please cancel duplicate flag, thank you. – ahdung Jul 30 '19 at 10:14
  • The linked answers explaining the situation even if the question is not the same. – thehennyy Jul 30 '19 at 11:25
  • @thehennyyI don't think so, this problem is about `DynamicInvoke`, no answer talk it. – ahdung Jul 31 '19 at 00:46

1 Answers1

1

I guess that problem in using of Action<int>, seems like it doesn't support dynamic invocation of optional args. This sample is working fine

// this method have a optional parameter
public static void Foo(int a = 3) { }

delegate void SampleDelegate(int a = 3);

static void Main(string[] args)
{
    SampleDelegate del = Foo;
    // pass Type.Missing
    del.DynamicInvoke(Type.Missing);
}
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
  • Thank you, but it cause method's defaultValue is ignored, i think this is a bug about `DynamicInvoke`, so depressing. – ahdung Jul 30 '19 at 10:06