为什么我会得到调用函数功能:LT时错误的结果; INT&GT ;? [英] Why am I getting wrong results when calling Func<int>?

查看:185
本文介绍了为什么我会得到调用函数功能:LT时错误的结果; INT&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码片段在C#中:

I have the following code snippet in C#:

var actions = new List<Func<int>>();

IEnumerable<int> values = new List<int> { 1, 2, 3 };

foreach (int value in values)
{
    actions.Add(() => value * value);
}

foreach (var action in actions)
{
    Console.WriteLine(action()); ;
}

Console.ReadLine();



它的运行很好,但我没有得到结果我期望的那样。

It's running fine, but I am not getting the result I expect.

实际结果

9,9,9

预期结果

1,4,9

为什么我不能得到结果我期望?

Why am I not getting the result I expect?

推荐答案

您正在捕捉你的lambda表达式中的循环变量,这意味着当代表终于调用的,它看到的最后的循环变量的值

You're capturing the loop variable within your lambda expression, which means when the delegate is finally invoked, it's seeing the final value of the loop variable.

简单的修正:

foreach (int value in values)
{
    int copy = value;
    actions.Add(() => copy * copy);
}



这样,你得到一个新的复制在循环的每次迭代变量,所以每位代表表达式将捕捉不同的变量,而且他们没有受到循环变量()切换时间。

This way you get a new copy variable in each iteration of the loop, so each delegate expression will capture a different variable, and they're not affected by the loop variable (value) changing over time.

埃里克利珀解释了这个井的关闭了被认为是有害的循环变量(和的part 2 )。

Eric Lippert explains this well in "Closing over the loop variable considered harmful" (and part two).

基本上这是一个在C疑难杂症#这几乎每个人都爱上了迟早的事情。

Basically this is a "gotcha" in C# which nearly everyone falls for sooner or later.

这篇关于为什么我会得到调用函数功能:LT时错误的结果; INT&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆