Using C# delegates with methods with optional parameters [duplicate]

拥有回忆 提交于 2019-12-04 02:49:06

问题


Is there a chance to make this code work? Of course I can make second definition of Foo, but I think it'd be a little non-elegant ;)

delegate int Del(int x);

static int Foo(int a, int b = 123)
{ 
    return a+b; 
}

static void Main()
{
    Del d = Foo;
}

回答1:


Your delegate asks for exactly one parameter, while your Foo() method asks for at most two parameters (with the compiler providing default values for unspecified call arguments). Thus the method signatures are different, so you can't associate them this way.

To make it work, you need to either overload your Foo() method (like you said), or declare your delegate with the optional parameter:

delegate int Del(int x, int y = 123);

By the way, bear in mind that if you declare different default values in your delegate and the implementing method, the default value defined by the delegate type is used.

That is, this code prints 457 instead of 124 because d is Del:

delegate int Del(int x, int y = 456);

static int Foo(int a, int b = 123)
{ 
    return a+b; 
}

static void Main()
{
    Del d = Foo;

    Console.WriteLine(d(1));
}



回答2:


Optional parameters do not change the signature of the method. They simply declare default values for the parameters. This information is used by the compiler to supply values when you omit them in your code. The compiled code will still pass arguments for all parameters.

In your case, the method Foo is still declared as taking two int arguments as input. There is no version of Foo that can be invoked with one parameter only (remember, the compiler fills in the blanks for you there). Any delegates used for invoking methods with optional parameters, need to explicitly include all parameters in order to match the signature.




回答3:


Optional parameters do not change the signature of the method, which is critical to delegates. It only appears to change the signature from the perspective of the caller. What you are trying to achieve cannot be done using the method you have attempted to use.

See this question: Optional parameters on delegates doesn't work properly



来源:https://stackoverflow.com/questions/5729154/using-c-sharp-delegates-with-methods-with-optional-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!