【问题标题】:Why do I get an error in the loop in this code?为什么我在此代码的循环中出现错误?
【发布时间】:2021-04-30 13:14:26
【问题描述】:

我可以使用“for”循环来做到这一点,但是为什么当我尝试使用“for each”时它会说它超出了数组的范围?文本文件编号为 9 2 1 3 4 4。

 string text = File.ReadAllText("txt.txt");         
            string[] bits = text.Split(' ');
            int[] numere = Array.ConvertAll(bits, int.Parse);
            

            
            foreach (int item in numere)
            {

                Console.WriteLine(numere[item]);
                
            }

【问题讨论】:

  • 您的数组包含 6 项,但您尝试在第一次迭代中访问索引 9。所以,你不能那样做。请尝试 Console.WriteLine(item);
  • 使用foreachitemnumere的一个元素,你得到numere[0]作为item,下一个numere[1]作为item等等,你不要不需要像使用for 那样进行索引。就像在网球试训课上:你从教练或机器那里得到一个球,一个球,一个球……直到篮子空了。因此@ofirelarat 的答案。

标签: c# arrays loops file


【解决方案1】:

您使用的 foreach 函数有误。 在 foreach 循环中,您每次迭代都迭代集合的项目值, 所以在你的例子中,item 变量是那个迭代中单元格的值,而不是他的索引(就像在常规 for 循环中一样)。

看起来像这样:

foreach (int item in numere)
{
    Console.WriteLine(item);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-05
    • 1970-01-01
    相关资源
    最近更新 更多