开发者

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

开发者 https://www.devze.com 2023-02-27 01:33 出处:网络
This question already has answers here: Optional parameters 开发者_运维百科on delegates doesn't work properly [duplicate]
This question already has answers here: Optional parameters 开发者_运维百科on delegates doesn't work properly [duplicate] (3 answers) Closed 9 years ago.

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;
}


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));
}


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消