传递静态值

本文关键字:静态 | 更新日期: 2023-09-27 18:03:39

所以我有一个int x,我需要传递给另一个函数,问题是x在我使用这个函数之前发生了变化,所以值x的变化与我想要的值不同。是否有一种方法来复制一个整数(我找不到)?那我的问题就解决了。

private void Init()
{
    for (int x = 0; x < 10; x++)
    {
        for (int y = 0; y < 10; y++)
        {
            Button tmpButton = new Button();
            tmpButton.Click += (sender, e) => ButtonClick(sender, e, x, y); 
            //x and y need to "freeze" their value at this point
        }
    }
}
private void ButtonClick(object sender, EventArgs e, int x, int y)
{
    Console.Out.WriteLine(x.ToString() + ":" y.ToString());
}

输出:"10:10"

预期输出(如果点击按钮3,4):"3:4"

传递静态值

这是一个闭包问题,可以通过使用临时变量

来解决。
int localX = x;
int localY = y;

要更好地理解捕获的变量,请参阅Jon Skeet对SO的回答

你应该使用一个临时变量:

for (int x = 0; x < 10; x++)
{
    for (int y = 0; y < 10; y++)
    {
        int tempX = x;
        int tempY = y;
        Button tmpButton = new Button();
        tmpButton.Click += (sender, e) => ButtonClick(sender, e, tempX, tempY); 
        //x and y need to "freeze" their value at this point
    }
}

当你在循环中捕获变量时,你应该总是小心。

基本上,发生的事情是你的lambda捕获变量和而不是变量的值。因此,当按钮被按下时,循环当然结束,变量的值为10。

Eric Lippert写了一个关于为什么会发生这种情况的系列文章。