添加方法以在“for”中委托更改迭代循环 - C#问题? [英] Adding method to delegate changes iteration in "for" loop - C# issue?

查看:162
本文介绍了添加方法以在“for”中委托更改迭代循环 - C#问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了C#代码的一些问题。添加方法以for循环委托i加1,所以for(int i = 0,i< x; i ++)必须改为for(int i = -1,i< x-1; i ++)正常工作。为什么?

I've faced some issue with C# code. Adding method to delegate in "for" loop increments "i" by one., so "for(int i = 0, i < x ; i++)" must be change to "for(int i = -1, i < x-1; i++)" to work correctly. Why is that?

以下代码抛出IndexOutOfRangeException

Code below throws an IndexOutOfRangeException

string[] names = new string[] { "John", "Madeline", "Jack", "Gabby" };
Action showNameDelegate = null;
for (int i = 0; i < names.Length; i++)
{
    showNameDelegate += () => global::System.Console.WriteLine(names[i]);
}
foreach (Action showName in showNameDelegate.GetInvocationList())
{
    showName();
}

正确的代码是(查看从-1开始的迭代器i但是names [-1]不存在):

Right code is (look at iterator "i" which starts from -1 but "names[-1]" does not exist):

string[] names = new string[] { "John", "Madeline", "Jack", "Gabby" };
Action showNameDelegate = null;
for (int i = -1; i < names.Length - 1; i++)
{
    showNameDelegate += () => global::System.Console.WriteLine(names[i]);
}
foreach (Action showName in showNameDelegate.GetInvocationList())
{
    showName();
}

这个答案是正确的(由Ed Plunkett提供):
每位代表引用变量i。它们都引用变量,因此当它们执行时,它们将获得它当时拥有的任何值。在for循环完成后执行委托。那时,我等于名字.Length。在循环体中创建i的本地副本 - 或者使用foreach循环,它会自动修复此问题。

This answer is correct (by Ed Plunkett): Each delegate references the variable i. They all reference the variable, so when they execute, they'll get whatever value it has right then. The delegates are executed after the for loop completes. At that point, i is equal to names.Length. Make a local copy of i in the body of the loop -- or use a foreach loop, which automatically fixes this issue.

推荐答案

您应该像这样更改您的代码;

You should change your code like this;

for (int i = -1; i < names.Length - 1; i++)
{
    string name = names[i];
    showNameDelegate += () => global::System.Console.WriteLine(name);
}

或者您可以尝试使用foreach。

Or you can try to use foreach.

这篇关于添加方法以在“for”中委托更改迭代循环 - C#问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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