【问题标题】:How to prevent "index" to updated itself in array of Action如何防止“索引”在 Action 数组中更新自身
【发布时间】:2019-04-12 09:06:13
【问题描述】:

当我用 for loopdelegate 添加到 Actionsarray 时,I 会在整个数组中更新。如何防止这种情况发生?

我尝试在添加之前将“I”分配给一个整数。

Action[] actions = new Action[100];

for (int i = 0;i< actions.Length; i++)
{
    actions[i] = () => Console.WriteLine("Hello"+ i);
}

Action[]中每个Action中的“I”为100;

这是为什么呢?

【问题讨论】:

标签: c# delegates action


【解决方案1】:

因为它们都分配给同一个局部变量“int i” 并且在循环结束后“i”为 100

Action[] actions = new Action[100];

for (int i = 0;i< actions.Length; i++)
{
    int a = i;
    actions[i] = () => Console.WriteLine("Hello"+ a);
}

在声明 int a = i 之后,每个动作都有各自的 a

【讨论】:

    【解决方案2】:

    HereHere 是对类似问题的很好解释。 Here 也是 Jon Skeet 对 C# 闭包的很好解释。

    for 循环中,只使用了一个变量i。这就是为什么稍后当您执行操作时,它们都引用相同的值i=100。如果动作需要使用当前i 的实际值,您必须捕获它的副本并将副本存储到动作。

    for (int i = 0;i< actions.Length; i++)
    {   
        int copy = i;
        actions[i] = () => Console.WriteLine("Hello"+ copy);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 2014-08-27
      • 2020-08-17
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多