For循环超出范围 [英] For loop goes out of range

查看:698
本文介绍了For循环超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.StartTasks();
        }
    }
    class MyClass
    {
        int[] arr;
        public void StartTasks()
        {
            arr = new int[2];
            arr[0] = 100;
            arr[1] = 101;

            for (int i = 0; i < 2; i++)
            {
                Task.Factory.StartNew(() => WorkerMethod(arr[i])); // IndexOutOfRangeException: i==2!!!
            }
        }

        void WorkerMethod(int i)
        {
        }
    }
}






看来我++中的循环迭代结束前被执行一次。为什么我得到IndexOutOfRangeException?


It seems that i++ gets executed one more time before the loop iteration is finished. Why do I get the IndexOutOfRangeException?

推荐答案

您正在关闭了循环变量。当它的时候了 WorkerMethod 来被调用, I 可以有两个值,0或1不是值

You are closing over loop variable. When it's time for WorkerMethod to get called, i can have the value of two, not the value of 0 or 1.

当您使用闭包要明白,你没有使用该变量的那一刻,你用变量本身的价值是很重要的。所以,如果你创建循环lambda表达式,像这样:

When you use closures it's important to understand that you are not using the value that the variable has at the moment, you use the variable itself. So if you create lambdas in loop like so:

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

和后来执行的行动,他们都将打印2,因为这是什么样的价值 I 是目前

and later execute the actions, they all will print "2", because that's what the value of i is at the moment.

在介绍循环中的局部变量将解决你的问题:

Introducing a local variable inside the loop will solve your problem:

for (int i = 0; i < 2; i++)
{
    int index = i;
    Task.Factory.StartNew(() => WorkerMethod(arr[index])); 
}



< ReSharper的即插即用GT; 这是一个原因尝试 ReSharper的 - 它给了很多帮助您捕捉这样一个早期的错误警告。 关闭了一个循环变量是他们当中的< / ReSharper的插件>

<Resharper plug> That's one more reason to try Resharper - it gives a lot of warnings that help you catch the bugs like this one early. "Closing over a loop variable" is amongst them </Resharper plug>

这篇关于For循环超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆