动作委托使用foreach循环外声明的变量的最后值 [英] Action delegate uses the last values of variables declared outside foreach loop

查看:78
本文介绍了动作委托使用foreach循环外声明的变量的最后值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

int i = 0;
foreach(var tile in lib.dic.Values)
{
    var ii = i;
    var t = tile;
    Button b = new Button( () = > { MainStatic.tile = t; } );
    Checkbox c = new Checkbox( () = > { lib.arr[ii].b = !lib.arr[ii].b; } );
    i++;
}

虽然上面的代码可以正常工作,但下面的代码:

While the above code works as it should, this piece below:

int i = 0;
foreach(var tile in lib.dic.Values)
{
    Button b = new Button( () = > { MainStatic.tile = tile; } );
    Checkbox c = new Checkbox( () = > { lib.arr[i].b = !lib.arr[i].b; } );
    i++;
}

...将始终使用最新值 i 和 tile 变量。为什么会发生这种情况,为什么我必须对这些变量进行本地复制,尤其是非引用类型 int i

…will always execute the delegates with the last values of i and tile variables. Why does this happen, and why do I have to make a local copy of those vars, especially non-reference type int i?

推荐答案

已知的问题,请查看Eric的博客关闭,捕获了变量。

Known "issue", please check Eric's blog Closures, captured variables.

Microsof决定进行重大更改,然后在C#5中进行修复。

Microsof decided to go for a breaking change, and fix it in C# 5.

这篇关于动作委托使用foreach循环外声明的变量的最后值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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