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

net*_*x01 0 c# lambda functional-programming

我真的很难理解为什么,当我改变我的代码使用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);
        }
    );
Run Code Online (Sandbox Code Playgroud)

此代码已更改为使用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)));
        }
    );
Run Code Online (Sandbox Code Playgroud)

这真让我生气,因为我不知道我做错了什么.有人可以帮忙吗?

谢谢,AG

Eli*_*sha 5

你想通过使用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)
{

}
Run Code Online (Sandbox Code Playgroud)

调用Response构造函数Action实际上会发送Action.如果Response有一个重载调用它并使用返回值,那么Action只有在Response实际使用它时才会出现(在构造函数调用期间不需要).

在你的例子中,工作将在调用期间完成,(_, 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
}
Run Code Online (Sandbox Code Playgroud)

除非Response期望Action它永远不会执行它的身体.