为什么执行lambda表达式中的方法

why method in lambda expression is executed

我有一个简单的测试程序,想知道为什么控制台 输出是 1 而不是 6? 谢谢。

static void Main(string[] args)
    {
        var t = new List<int>() {1, 1, 1, 1, 1};
        var s = new List<int>() {1};

        var g = t.Select(a => test(a, s));
            Console.WriteLine(s[0]);    
    }

    private static int test(int a, List<int> s )
    {
        s[0]++;
        return a;
    }

IEnumerable is lazy。直到需要时才计算表达式,因此永远不会调用 test

添加 Console.WriteLine(g.ToList());,您将看到现在如何调用 test 方法。您可以使用以下方法在您的代码中强制对它求值:var g = t.Select(a => test(a, s)).ToList(); 这将导致可枚举值被求值到一个列表中。

参见Lazy Evaluation

In programming language theory, lazy evaluation, or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations (sharing).

注意:一般不鼓励使用会产生副作用的LINQ代码,见this blog post第4段。