Confusion over `Action` delegate and lambda expressions(对“Action委托和 lambda 表达式的困惑)
问题描述
private void StringAction(string aString) // method to be called
{
return;
}
private void TestDelegateStatement1() // doesn't work
{
var stringAction = new System.Action(StringAction("a string"));
// Error: "Method expected"
}
private void TestDelegateStatement2() // doesn't work
{
var stringAction = new System.Action(param => StringAction("a string"));
// Error: "System.Argument doesn't take 1 arguments"
stringAction();
}
private void TestDelegateStatement3() // this is ok
{
var stringAction = new System.Action(StringActionCaller);
stringAction();
}
private void StringActionCaller()
{
StringAction("a string");
}
我不明白为什么 TestDelegateStatement3
有效但 TestDelegateStatement1
失败.在这两种情况下,Action
都提供了一个采用零参数的方法.他们可能调用一个采用单个参数(aString
)的方法,但这应该是无关紧要的.他们不带参数.这只是不可能与 lamda 表达式有关,还是我做错了什么?
I don't understand why TestDelegateStatement3
works but TestDelegateStatement1
fails. In both cases, Action
is supplied with a method that takes zero parameters. They may call a method that takes a single parameter (aString
), but that should be irrelevant. They don't take a parameter. Is this just not possible to do with lamda expressions, or am I doing something wrong?
推荐答案
如你所说,Action 不带任何参数.如果你这样做:
As you said, Action doesn't take any parameters. If you do this:
var stringAction = new System.Action(StringAction("a string"));
这里是你实际执行的方法,所以那不是方法参数.
You actually execute the method here, so that is not a method parameter.
如果你这样做:
var stringAction = new System.Action(param => StringAction("a string"));
你告诉它你的方法有一个名为 param
的参数,而 Action 没有.
you tell it that your method takes a parameter called param
, which Action does not.
所以正确的做法是:
var stringAction = new System.Action( () => StringAction("a string"));
或更紧凑:
Action stringAction = () => StringAction("a string");
空括号用于表示 lambda 不带任何参数.
the empty brackets are used to indicate the lambda doesn't take any parameters.
这篇关于对“Action"委托和 lambda 表达式的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对“Action"委托和 lambda 表达式的困惑
基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01