为什么我不能在for循环中放置else-if语句?

时间:2016-12-12 20:05:13

标签: c# if-statement for-loop

可能是一个非常愚蠢的问题,但这是我的代码:

if (currentItem.Name == "MicrometerTags.index")
{
    histIndex = Convert.ToInt32(currentValue);
}

for (int k = 1; k <= 20; k++)
{
    else if (currentItem.Name == "MicrometerTags.meas" + k)
    {
        Properties.Settings.Default["meas" + k] = currentValue;
    }
}

Visual Studio告诉我for循环下的第一个{有一个错误,因为它期待}。但是你可以看到我的右支撑吗?我认为else-if语句在这里做错了。

编辑:好的,我不知道你不能做到这一点。那么有没有更好的方法来检查currentItem是否等于我的20个测量中的一个而不是手动写出20个if语句?

EDIT2:这是我试图制作的代码。感谢BlueMonkMN的解决方案。

            if (currentItem.Name == "MicrometerTags.index")
            {
                histIndex = Convert.ToInt32(currentValue);
            }

            else for (int k = 1; k <= 20; k++)
            {
                if (currentItem.Name == "MicrometerTags.meas" + k)
                {
                    Properties.Settings.Default["meas" + k] = currentValue;
                }
            }

1 个答案:

答案 0 :(得分:3)

if语句之后的结束括号有效地关闭了if语句,此时不再有活动&#34; if block&#34;

if (something == true)
{  // open the if block

} // close the if block

// no more if block in action here...

为了让其他人工作,需要在结束括号后立即进行:

if (something == true)
{  // open the if block

} // close the if block

else // next statement must be else for this to work
{  // open else block

}  // close else block

通常,这是用以下语法编写的:

if (someCondition) {
    // if true do this
} else {
    // otherwise do this
}

请注意,else仍然是if块的右括号之后的下一个语句。

你的工作原因是你在关闭if括号和else语句之间有其他语句。从逻辑上讲,我不确定你要做什么,但语法方面,以下是合法的:

if (someCondition == true) {
    // do stuff 
} else {
    for(int i = 0; i < someCount; i++) {
        // do stuff
    }   
}

for (int i = 0; i < someCount; i++) {

    if (someCondition == true) {
        // do stuff
    } else {
        // do other stuff
    }

}

请注意if和for块的打开和关闭顺序。如果IF首先打开,它必须最后关闭。如果for首先打开,它必须最后关闭(也就是最后一个输出模式)。这种模式对于任何编程语言都是有用的,并不仅限于ifs和fors,而是限于任何块级编程(甚至是名称空间,类,方法等)。

这也适用于嵌套逻辑:

if (condition1 == true) {

    if (condtion2 == true) 
    {

        // stuff

    }   // end condition2's if block 
    else 
    {

        // stuff

    }   // end condition2's else block


} // end condition 1's if block
else 
{

    // other stuff

}   // end condition 1's else block