缩短if语句具有相同条件

Dem*_*ier 0 c# dry

我在boolB这里比较两次,这段代码看起来需要改进.是否有可能写出这种不同的方法来减少代码重复?

if (boolA)
{
  if (boolB)
  {
    return "A";
  }

  return "B";
} 

if (boolB)
{
   return "C";
}

return "D";
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

好吧,你可以使用条件运算符使其更清晰 - 至少对我而言:

return boolA && boolB ? "A"
    : boolA ? "B"
    : boolB ? "C"
    : "D";
Run Code Online (Sandbox Code Playgroud)

一旦习惯了这种编写多个条件运算符的方式,它就会非常清楚地看作是一种伪模式匹配方法.

诚然,这确实可以多次评估条件.有办法避免这种情况,但我不确定它们是否很好...例如:

int bits = (boolA ? 2 : 0) | (boolB ? 1 : 0);
switch(bits)
{
    case 3: return "A";
    case 2: return "B";
    case 1: return "C";
    case 0: return "D";
    default: throw new InvalidOperationException("The world has gone mad!");
}
Run Code Online (Sandbox Code Playgroud)

或者使用不同的方法来嵌套条件:

return boolA ? (boolB ? "A" : "B")
    : boolB ? "C"
    : "D";
Run Code Online (Sandbox Code Playgroud)

这仍然是两次表达的 boolB一种情况,请注意.