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 表达式的困惑
基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
