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

时间:2009-10-23 10:16:32

标签: c# functional-programming lambda

我真的很难理解为什么,当我改变我的代码以使用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

1 个答案:

答案 0 :(得分: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)
{

}

使用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
}

除非Response期望Action,否则永远不会执行其正文。