您不需要 multilpe if 块来执行代码,因为您只是在做两件事中的一件,执行循环或不执行循环(一个 if 和一个 else)。如图here 所示,您可以使用单个布尔表达式来表示您是否应该跳过该循环迭代。
(x > 5) && (!DateTime.TryParse(y, out z) || w.CompareTo(z) == -1)
话虽如此,在循环中包含这样的复杂条件会妨碍可读性。就个人而言,我会简单地将这个条件提取到一个方法中,以便循环看起来像这样:
while(!done) // or whatever the while loop condition is
{
if(itemIsValid(x, y, w, out z))
{
//the rest of your loop
}
}
//it may make sense for x, y, w, and possibly z to be wrapped in an object, or that already may be the case. Consider modifying as appropriate.
//if any of the variables are instance fields they could also be omitted as parameters
//also don't add z as an out parameter if it's not used outside of this function; I included it because I wasn't sure if it was needed elsewhere
private bool itemIsValid(int x, string y, DateTime w, out DateTime z)
{
return (x > 5)
&& (!DateTime.TryParse(y, out z) || w.CompareTo(z) == -1)
}
这有几个优点。首先,它是一种无需 cmets 即可自行记录代码的方式。查看循环时,您可以将其理解为“当我还没有完成时,如果项目有效,请执行所有这些操作”。如果您对如何定义有效性感兴趣,请查看该方法,否则请跳过它。您还可以将方法重命名为更具体的名称,例如“isReservationSlotFree”或它实际代表的任何名称。
如果您的验证逻辑很复杂(这有点复杂),它允许您添加 cmets 和解释,而不会弄乱更复杂的循环。