可能是一个超级愚蠢的问题,但这是我的代码:
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;
}
}
if语句后的右括号有效地关闭了if语句,此时不再有活动的“ if块”
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首先打开,则必须最后关闭(aka,先进先出模式)。这种模式对于任何一种编程语言都是基本的,并且不仅限于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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句