c# - 需要帮助简化嵌套的 if block

标签 c# if-statement simplification

我有以下代码块:

if (x > 5)
{
    if (!DateTime.TryParse(y, out z))
        break;
    if (w.CompareTo(z) == -1)
        break;
}

其中 x 是整数,y 是字符串,z 和 w 是 DateTime 变量。break; 的原因是整个 block 驻留在一个循环中。

有什么方法可以简化它以使其更易于阅读?

最佳答案

你不需要多重 if block 来执行代码,因为您只做两件事中的一件,执行循环或不执行循环(一个 if 和一个 else)。如图here您可以使用单个 bool 表达式来表示是否应该跳过该循环迭代。

(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)
}

这有几个优点。首先,它是一种无需注释即可自行记录代码的方式。查看循环时,您可以将其理解为“当我还没有完成时,如果项目有效,请执行所有这些操作”。如果您对如何定义有效性感兴趣,请查看该方法,否则请跳过它。您还可以将该方法重命名为更具体的名称,例如“isReservationSlotFree”或它实际代表的任何名称。

如果您的验证逻辑很复杂(这有点复杂),它允许您添加注释和解释,而不会弄乱更复杂的循环。

关于c# - 需要帮助简化嵌套的 if block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12627115/

相关文章:

c# - VSTO 字加载项 : MessageBox Timing Issue

c# - 我如何检查 session 是否存在或是否为空值或 .net c# 中的 null

java - 可以设置 if 语句来搜索文本文件中的特定模式吗?

powershell - 在 “time”语句中使用Get-date “if” PowerShell

c++ - 寻找可以简化的过于复杂的 boolean 表达式的工具?

algorithm - 需要图形简化算法建议

c# - 如何设置消息队列的所有者?

c# - 在 HttpClient 中将多个 token 添加到 DefaultRequestHeaders.Authorization

python - 太多的 if 语句

input - boolean 代数简化(3 个输入)