对“Action"委托和 lambda 表达式的困惑

Confusion over `Action` delegate and lambda expressions(对“Action委托和 lambda 表达式的困惑)

本文介绍了对“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 表达式的困惑

基础教程推荐