【问题标题】:How does `foreach` iterate through a 2D array?`foreach` 如何遍历二维数组?
【发布时间】:2015-04-07 18:35:38
【问题描述】:

我很好奇 C# 中的 foreach 循环如何遍历多维数组。在下面的代码中,第二个嵌套的for 循环最初是一个foreach,它会给出放置在循环中的不正确的音高位置。我知道很难凭直觉知道它的作用,但基本上是这样的:将音高放入一个多维数组(这里,numVoices 为 2,exLength 为 10),这样您将拥有一个 2x10 的音高数组;然后,MIDI 输出设备同时播放这些音高行中的每一行。当我使用foreach 将音高的名称放入字符串中以便我可以显示网格内哪个位置的音高时,foreach 会以“错误”的顺序显示它们(即 [ 0,3] 在音高网格中不是字符串中打印的内容)。使用嵌套的for,这个问题就消失了。我尝试使用ints(下面的代码)的二维列表的较小示例重新创建它,但这次它给出了“正确”的答案。为什么?

            //put pitches into grid
            //numVoices = 2, exLength = 10 (10 notes long, 2 voices)
            for (int i = 0; i < numVoices; i++ )
            {
                for(int j = 0; j < exLength; j++)
                {
                    //here we generate random pitches in different octaves
                    //depending on the voice (voice 2 is in octave
                    //below voice 1, etc)
                    randnum = (random.Next(100 - (i * 13), 112 - (i * 13)));                        

                    melodyGrid[j, i] = (Pitch)randnum;

                }
            }

            for (int i = 0; i < numVoices; i++)
            {
                for (int j = 0; j < exLength; j++)
                {
                                     //this down here makes it more readable for
                                     //humans
                                     //e.g. "FSharp5" becomes "F#5"

                    noteNames += String.Format("{0, -6}", melodyGrid[j,i].ToString().Replace("Sharp", "#").Replace("Flat", "b"));

                }
                noteNames += "\r\n"; //lower voices are just separated by newlines
            }
            Console.WriteLine(noteNames);

以下代码“正常”运行:

int[,] nums = { {1, 2, 3}, 
                            {4, 5, 6},
                            {7, 8 ,9} };
            foreach (int i in nums)
            {
                Console.Write("{0} ", i);
            }

有没有可能我只是犯了一个语义错误?还是foreach 循环以不同的方式遍历数组?

【问题讨论】:

    标签: c# arrays for-loop multidimensional-array foreach


    【解决方案1】:

    我很好奇 C# 中的 foreach 循环如何遍历多维数组。

    对于此类问题,最终权威是 C# 语言规范。在这种情况下,第 8.8.4 节:

    foreach 遍历数组元素的顺序如下:对于一维数组,元素按索引递增的顺序遍历,从索引 0 开始,以索引 Length – 1 结束。对于多维数组,遍历元素使得最右边维度的索引首先增加,然后是下一个左边的维度,以此类推。

    现在,将其与您使用 for 语句进行迭代的方式进行比较:

    for (int i = 0; i < numVoices; i++ )
    {
        for(int j = 0; j < exLength; j++)
        {
            ...
            melodyGrid[j, i] = (Pitch)randnum;
    

    换句话说,您首先增加 leftmost 维度...所以是的,这将给出与foreach 不同的结果。如果您想使用foreach 但获得相同的迭代顺序,则需要切换语音和长度的索引。或者,如果您想保持相同的索引顺序,只需使用 for 循环即可。

    【讨论】:

      猜你喜欢
      • 2016-04-06
      • 2011-07-18
      • 2016-09-04
      • 1970-01-01
      • 2013-03-14
      相关资源
      最近更新 更多