【发布时间】: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