我有一个简单的测试程序,想知道为什么控制台 输出是 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 段.
关于c# - 为什么执行lambda表达式中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31845669/