楼主:
uranusjr (â†é€™äººæ˜¯è¶…級笨蛋)
2015-04-07 22:51:58※ 引述《jamod (jasper)》之铭言:
: 小弟觉得应该是发生Closure的问题吧?
: 我想在10个按钮上面挂10个触发事件,Code大致上像:
: for(int index = 0;index < 10;index++){
: btn[index].onClick += () =>
: {
: Console.WriteLine(index.toString());
: };
: }
: 结果10个按钮按下去,都是10...
for (int i = 0; i < 10; i++) {
int localVariable = i;
btn[i].onClick += () => {
Console.WriteLine(localVariable.toString());
};
}
这里的问题是因为你只宣告了一个 index
所有的 closures 都会 capture 到同一个变量, 而这个变量又是 loop index
当 i++ 时, 所有 closures 都会被影响(因为它们使用的变量是同一个东西)
解法就是为每一个 closure 宣告一个 local variable 来 capture
在这里, 等于每个 iteration 都会把 loop index 复制一份
所以每个 closure capture 到的变量会是独立的, 也与 loop index 独立
就可以绕过你的问题