c# - 将可选参数和命名参数与 Action 和 Func 委托(delegate)一起使用

标签 c# delegates

为什么不能执行以下操作:

Func<int, int, int> sum = delegate(int x, int y = 20) { return x + y; };

Action<string, DateTime> print = 
    delegate(string message, DateTime datetime = DateTime.Now) 
    { 
        Console.WriteLine(message);
    };

sum(x: 20, y: 40);
print(datetime: DateTime.Now, message: "Hello");

只有命名参数的情况:

Func<int, int, int> sum = delegate(int x, int y) { return x + y; };

Action<string, DateTime> print = 
    delegate(string message, DateTime datetime) 
    { 
        Console.WriteLine("{0} {1}", message, datetime);
    };

Console.WriteLine(sum(y: 20, x: 40));
print(datetime: DateTime.Now, message: "Hello");

只有可选参数的情况:

Func<int, int, int> sum = delegate(int x, int y = 20) { return x + y; };

Action<string , DateTime> print = 
    delegate(string message, DateTime datetime = DateTime.Now)
    { 
        Console.WriteLine("{0} {1}",message, datetime);
    };

Console.WriteLine(sum(40));
print("Hello");

最佳答案

如前所述here -

Optional parameters are an attribute of a method or delegate parameter. When you call a signature (method or delegate) that has a known optional parameter at compile-time, the compiler will insert the optional parameter value at the callsite.

The runtime is not aware of optional parameters, so you can't make a delegate that inserts an optional parameter when it's called.

因此,要使用它,您必须提取出在编译时已知的具体实现(自定义委托(delegate)),并将调用站点的参数替换为可选参数,也可以使用命名参数。

声明自定义委托(delegate)-

public delegate int FuncDelegate(int x, int y = 20);

现在你可以在方法体中使用它了——

FuncDelegate sum = delegate(int x, int y) { return x + y; };
int result = sum (x : 20, y: 40 );
result = sum(20);

此外,只有编译时间常量可以在默认参数列表中使用。 但是 DateTime.Now 不是编译时常量,因此它也不能用于为参数指定可选值。

所以对于 Action 部分,这将起作用 -

public delegate void ActionDelegate(string message,
                                    DateTime dateTime = default(DateTime));

现在在这里使用委托(delegate) -

ActionDelegate print =
                delegate(string message, DateTime dateTime)
                { Console.WriteLine(dateTime.ToString()); };
print(dateTime: DateTime.Now, message: "SomeThing");

关于c# - 将可选参数和命名参数与 Action 和 Func 委托(delegate)一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19751811/

相关文章:

c# - 为什么 C# 默认将方法实现为非虚拟的?

c# - C#中的批处理文件执行

groovy - 从 Groovy 中的函数调用闭包的委托(delegate)方法?

c# - lambda c# 中 "() =>"的用途是什么

.net - 为什么从表达式动态生成的委托(delegate)比硬编码的 lambda 慢?

c# - 获取两个日期时间之间的所有月份和年份

c# - 无法使用 File.Move 创建已存在的文件

c# - 递归和 await/async 关键字

swift - Swift 中未通过委托(delegate)调用函数

c# - InvokeRequired 属性的值何时更改?