理解c#lambda表达式变量捕获
>在C#编程中的常见问题涉及循环中的lambda表达式。 Lambda表达式捕获变量的方式会导致意外结果。 让我们探索这个问题及其解决方案。
考虑此代码:
<code class="language-csharp">List<Func<int>> actions = new List<Func<int>>(); int variable = 0; while (variable < 10) { actions.Add(() => variable * 2); ++variable; } foreach (var act in actions) { Console.WriteLine(act.Invoke()); }</code>
>预期输出是偶数数字的序列(0、2、4、6、8)。 但是,实际输出为五个10。 之所以发生这种情况,是因为每个lambda表达式捕获参考>,而不是其创建时的值。 到调用lambdas时,variable
>已经达到其最终值为10。variable
>
为了纠正这一点,我们需要在每个lambda表达式的范围内创建一个循环变量的副本:
现在,每个lambda表达式在创建时捕获了其自己的
>值的独立副本,产生了预期的输出。<code class="language-csharp">List<Func<int>> actions = new List<Func<int>>(); int variable = 0; while (variable < 10) { int copy = variable; // Create a copy of the variable actions.Add(() => copy * 2); ++variable; } foreach (var act in actions) { Console.WriteLine(act.Invoke()); }</code>
c#5和foreach loopsvariable
>重要的是要注意,这种行为对C#5和更高版本中的循环的关注不大。编译器在中以不同的方式处理变量捕获,以防止此问题。 但是,显式复制方法仍然是与旧C#版本的清晰度和兼容性的最佳实践。 使用这种方法可确保所有C#版本和循环类型的一致行为。
>以上是为什么c#lambda循环中的表达式捕获最终变量值,以及如何修复?的详细内容。更多信息请关注PHP中文网其他相关文章!