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# 委托与带有可选参数的方法一起使用


基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01