混乱`Action`委托和lambda表达式 [英] Confusion over `Action` delegate and lambda expressions

查看:188
本文介绍了混乱`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 失败。在这两种情况下,动作与该接受零参数的方法提供。他们可能的呼叫的是只有一个参数( 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?

推荐答案

正如你所说,行动没有按' t拍摄任何参数。
。如果你这样做:

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"));



你告诉它,你的方法接受一个名为参数参数,其操作不会

因此,要做到这一点,正确的方法是:

So the correct way to do this would be:

var stringAction = new System.Action( () => StringAction("a string"));

或更紧凑的:

Action stringAction = () => StringAction("a string");



空括号是用来标明拉姆达不带任何参数。

the empty brackets are used to indicate the lambda doesn't take any parameters.

这篇关于混乱`Action`委托和lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆