[问题] Closure的问题

楼主: jamod (jasper)   2015-04-07 20:37:27
小弟觉得应该是发生Closure的问题吧?
我想在10个按钮上面挂10个触发事件,Code大致上像:
for(int index = 0;index < 10;index++){
btn[index].onClick += () =>
{
Console.WriteLine(index.toString());
};
}
结果10个按钮按下去,都是10...
试了很久都没找到解决方式,目前是采用类似分成10段来写的方法,
但我觉得这应该是很常见的状况,应该有更合理的解决办法吧?
想请问有没有高手能帮我解答一下,非常感谢~
以下附上一段Sample Code:
class Program
{
static Button[] btnArray;
static void Main(string[] args)
{
btnArray = new Button[10];
for (int index = 0; index < 10; index++) {
btnArray[index] = new Button();
btnArray[index].onClick += () =>
{
Console.WriteLine(index.ToString());
};
}
foreach (Button btn in btnArray) {
btn.Click();
}
Console.ReadKey();
}
}
class Button {
public delegate void Del();
public event Del onClick;
public void Click() {
onClick();
}
}
希望的要求是能够列出 1~10,但结果都是10
作者: J002 (阿里山 我来了XD~)   2015-04-07 20:53:00
可以po完整一点的code吗?
作者: GoalBased (Artificail Intelligence)   2015-04-07 21:11:00
你可以写一个sample code
作者: wenyonba (射后不理很XX啊!!!!)   2015-04-07 21:40:00
你的问题是不是你10个Button的OnClick事件,是要指向同一函式,但是函式内你却不知道是哪个按钮触发了事件????

Links booklink

Contact Us: admin [ a t ] ucptt.com