For循环超出范围

编程入门 行业动态 更新时间:2024-10-25 18:29:06
本文介绍了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循环超出范围

本文发布于:2023-10-16 12:19:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497536.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!