Using C# delegates with methods with optional parameters(将 C# 委托与带有可选参数的方法一起使用)
问题描述
有没有机会让这段代码工作?当然,我可以对 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# 委托与带有可选参数的方法一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 C# 委托与带有可选参数的方法一起使用


- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01