相关疑难解决方法(0)

混淆`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");
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么TestDelegateStatement3工作但TestDelegateStatement1 …

c# lambda delegates

9
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×1

delegates ×1

lambda ×1