这里有一些答案和explenations他们在后端如何运行的(如理解为什么会帮助你在长期运行)
一个简单的回答提出的每一个后续if
语句之前,使用else
像这样
public void Method()
{
if (flagIsUp)
{
if (x == 1)
//code here;
else if (y == 2)
//code here;
else if (z == 3)
//code here;
}
if (buttonPressed)
{
//code here;
}
}
什么这最终运行像编译后更像
public void Method()
{
if (flagIsUp)
{
if (x == 1)
{
//code here;
// Excecution skips to 'x==1 fastforward'
}
else
{
if (y == 2) // intentional indentation
{
//code here;
// Excecution skips to 'y==1 fastforward'
}
else
{
if (z == 3) // intentional indentation
{
//code here;
}
} // y==2 fast forward
} // x==1 fast forward
}
if (buttonPressed)
{
code here;
}
}
这样的安排显示了如何如果条件里面否则,如果“缩进”子程序。如果A是真的,那么它将跳过B和C的代码。如果A为假,且B为真,则C被跳过。如果A和B是错误的C被检查。
另一种方式来完成,这是把这个检查到它自己的私有方法,并从它返回时的真实条件满足
public void Method()
{
if (flagIsUp)
DoFlagUpCheck();
if (buttonPressed)
{
//code here;
}
}
private void DoFlagUpCheck()
{
if (x == 1)
{
//code here;
return; // Stop and return to Method()
}
if (y == 2)
{
//code here;
return; // Stop and return to Method()
}
if (z == 3)
{
//code here;
return; // Stop and return to Method()
}
}
这样,代码停止执行,并从该方法返回第一个真实的情况。如果A是真的,那么做代码并返回,否则继续B ...
有一件事值得考虑的是,程序是否可以重构,使得X,Y和Z可以用单个枚举表示?由于x==1
,y==2
和z==3
是相互排斥的,有可能是一个方法,使这一套更易读条件和东西最终会更像
public Method()
{
if (flagIsUp)
{
switch(flagCondition)
{
case FlagX:
//code here;
break;
case FlagY:
//code here;
break;
case FlagZ:
//Code here;
break;
}
}
if (buttonPressed)
{
//code here;
}
}
最后,它往往是有益的,对性能,放置最有可能的情况是第一。
'x','y'和'z'是否真的将变量分开? – ChrisF 2012-03-03 18:46:42
这不会编译,你需要==不= =(比较vs assignemnt) – 2012-03-03 18:49:59
它也不会编译,因为“代码在这里”是无效的代码 - 我认为这是伪代码。 – Krumelur 2012-03-03 18:51:35