Anonymous c# delegate within a loop

2019-01-20 08:06发布

Hi all i am trying to write and anonymous delegate. as the integer variable is shared among the delegate i need it to be the local instance of every delegate such that rs[0] always gets nics[0], rs[1] always gets nics[1] and so on... how will i achieve this.

for (int i = 0; i < nics.Count; i++)
   {
         rs[i] = new RollingSeries(monitor, new RollingSeries.NextValueDelegate(delegate()
         {
            return GetNetworkUtilization(nics[i]);
          }));
    }

Abdul khaliq

标签: c# delegates
3条回答
Animai°情兽
2楼-- · 2019-01-20 08:09

Make a local copy of i:

   for (int i = 0; i < nics.Count; i++)
   {
         int j = i;
         rs[i] = new RollingSeries(monitor, new RollingSeries.NextValueDelegate(delegate()
         {
            return GetNetworkUtilization(nics[j]);
          }));
    }

The Beauty of Closures

查看更多
唯我独甜
3楼-- · 2019-01-20 08:16

Put int j = i inside your loop and refer to j within the lambda expression.

If you are curious about why this happens, here is an MSDN blog entry containing a detailed technical explanation: Closing over the loop variable considered harmful

查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-20 08:22

Use a local to get a different value per iteration

for (int i = 0; i < nics.Count; i++)
   {
         int localI = i;
         rs[i] = new RollingSeries(monitor, new RollingSeries.NextValueDelegate(delegate()
         {
            return GetNetworkUtilization(nics[localI]);
          }));
    }
查看更多
登录 后发表回答