循环遍历数组问题的内容

use*_*981 5 c#

我使用int数组来保存一长串整数.对于这个数组的每个元素,我想检查它是否为1,如果是,那么只做与1相关的东西,否则如果它是2,则执行与2相关的其他内容,依此类推存储在数组中的每个值.我想出了下面的代码,但它没有按预期工作,有什么我想念的吗?发生的事情是只考虑数组的第一个值.

int[] variable1 = MyClass1.ArrayWorkings();
foreach (int i in variable1)
{ 
    if (variable1[i] == 1)
    {
        // arbitrary stuff
    }
    else if (variable1[i] ==2)
    {
        //arbitrary stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

O. *_*per 8

所述iforeach环保持从在每个迭代阵列,而不是索引的实际元素值.在您的特定代码示例中,您的数组可能只包含零,这就是为什么您只获取第一个元素(您总是使用索引0).因此,你应该检查i而不是variable1[i].

如果你要检查各种整数常量,switch表达式更合适,BTW:

foreach (int i in variable1) {
    switch (i) {
        case 1:
            // arbitrary stuff
            break;
        case 2:
            // arbitrary stuff
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

switch/ case节省一些写作; 如果你拉从其他地方比你的价值观i,你可以简单地改变(i)的部分switch语句,而且,switch可能会由编译器比链接更有效地评估if- else报表.

注意:您将无法直接更改foreach循环中的数组值,因为您无法分配任何内容i.如果需要分配新的数组值,则必须这样做

  • 在使用foreach或时仍然使用其他变量来计算自己
  • 使用另一个循环,例如for自己检索当前索引处的项目.


McG*_*gle 4

你试图做一些没有意义的事情。要了解它是如何工作的,举一个简单的例子,一个包含值的数组:9,4,1。

如果您尝试在此示例数组上运行代码,您将收到错误:

foreach (int i in variable1)
{ 
    if (variable1[i] == 1)   // the item i is 9.  
                             // But variable[i] means, get the value at position #9 in the array
                             // Since there are only 3 items in the array, you get an Out Of Range Exception
    {
        // arbitrary stuff
    }
{
Run Code Online (Sandbox Code Playgroud)

相反,这就是您所需要的:

foreach (int i in variable1)  // i will be 9, then 4, then 1)
{ 
    if (i == 1)   
    {
        // arbitrary stuff
    }
    // ... etc
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用for循环,它会给出索引 0、1 和 2,如下所示:

for (int i=0 ; i<=variable1.Length ; i++)   // i will be 0, 1, 2
                                            // variable[i] will be 9, 4, 1
{
    if (variable1[i] == 1) 
    { 
        // stuff
    }

    // ... etc
}
Run Code Online (Sandbox Code Playgroud)