问题描述
有没有机会让这段代码工作?当然,我可以对 Foo 进行第二个定义,但我认为它有点不优雅;)
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;
}
推荐答案
您的委托要求恰好一个参数,而您的 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.
要使其工作,您需要重载 Foo()
方法(如您所说),或使用可选参数声明您的委托:
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.
也就是说,这段代码打印的是 457
而不是 124
因为 d is Del
:
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));
}
这篇关于将 C# 委托与带有可选参数的方法一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!