繁体   English   中英

这个lambda表达式有什么问题?

[英]What is wrong with this lambda expression?

我真的很难理解为什么,当我更改代码以使用lamdba表达式时,它不起作用。

此代码可以在控制台上运行并打印:

object dummy = new object();
InterServer.ExecuteDataReader(new InterServerRequest(ServerID.a_01, "dbo.getbooks") 
    { 
        Params = new Dictionary<string, object> { 
            { "Tool", "d1" }, 
            { "Loc", locale == string.Empty ? null : locale } } 
    },
    (_, reader) =>
        {
            reader.AsEnumerable(r => (r.GetString(r.GetOrdinal("book")))).ToList().ForEach(Console.WriteLine);
            return new Response(dummy);
        }
    );

该代码已更改为使用lambda表达式; 它什么也没打印,我不明白为什么:

InterServer.ExecuteDataReader(new InterServerRequest(ServerID.a_01, "dbo.getbooks")
    { 
        Params = new Dictionary<string, object> { 
            { "Tool", "d1" }, 
            { "Loc", locale == string.Empty ? null : locale } } 
    },
    (_, reader) =>
        {
            return new Response(new Action(() => 
                reader.AsEnumerable(r =>(r.GetString(r.GetOrdinal("book")))).ToList().ForEach(Console.WriteLine)));
        }
    );

这真让我发疯,因为我看不出自己做错了什么。 有人可以帮忙吗?

谢谢,AG

您想通过使用Lambda表达式来实现什么?

在这个例子中, Action不会被调用,因此没有任何反应。 Action被调用时,您将看到输出。

Action不是隐式执行的。

例如:

public void Call()
{
    // Call with int argument 1
    DoSomething(1);

    // Call with Func that returns 1
    // It'll never produce the value unless Func is invoked
    DoSomething(new Func<int>(() => 1));

    // Call with Func explicitly invoked
    // In this case the body of the lambda will be executed
    DoSomething(new Func<int>(() => 1).Invoke());
}

public void DoSomething(object obj)
{

}

使用Action调用Response构造函数实际上将发送Action 如果Response有一个调用它并使用返回值的重载,则该Action仅在Response实际使用它时才会出现(在构造函数调用中不必要)。

在您的示例中,无论如何在调用(_, reader) => ...过程中都会完成工作(_, reader) => ...因此不会“太早”完成工作。

为了清楚起见(最后一个示例,我添加了:)):

public void Call()
{
    DoSomething(new Action(() => Console.WriteLine("Arrived")));
}

public void DoSomething(Action obj)
{
    int x = 0; // Nothing printed yet
    Action storedAction = obj; // Nothing printed yet
    storedAction.Invoke(); // Message will be printed
}

除非Response期望有一个Action ,否则它将永远无法执行其主体。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM