我的游戏中有一个GUI设置代码,比如:
for (int i = 0; i < count; i++)
{
...
Button button = new Button();
...
button.handler = delegate { selectedIndex = i; };
gui.Add(button);
...
}我想让按钮将selectedIndex更改为i的当前值,这是在它创建的时候。也就是说,button0将其更改为0,button1更改为1,依此类推。但是,看起来它在委托到i变量中的链接值,并且所有的按钮都将selectedIndex更改为count + 1。怎么修呢?
发布于 2014-02-24 11:44:15
您将遇到匿名函数中捕获的内容的共同问题。您要在委托中捕获i,该值在循环过程中会发生变化。
你需要一份i的副本
for (int i = 0; i < count; i++)
{
int copy = i;
...
Button button = new Button();
...
button.handler = delegate { selectedIndex = copy; };
gui.Add(button);
...
}注意,foreach循环在C# 4中有相同的问题,但是在C# 5中,foreach循环中的迭代变量在每次迭代中都是一个“新鲜”变量。
https://stackoverflow.com/questions/21986679
复制相似问题