并非所有代码路径都返回一个值 - 但它们确实存在

m.e*_*son 4 .net c# compiler-errors value-type

以下代码提取无法编译导致not code paths return a value.这两种类型Test1StandardChargeCalculator,并Test2StandardChargeCalculator从返回类型的.

我知道如何解决这个问题,但我的问题是我为什么要这样做?A bool是值类型 - 因此只能表示truefalse,这两个都在此代码段中得到满足.那么编译失败的原因呢?

internal StandardChargeCalculator Create()
{
      bool value = true;

      switch (value)
      {
          case true:
              return new Test1StandardChargeCalculator();
          case false:
              return new Test2StandardChargeCalculator();
      }
} //not all code paths return a value
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 15

使用switch语句时,编译器不理解当您使用布尔类型打开时,只能有两个结果.

发生错误是因为您没有默认情况.

不要使用switch布尔测试 - 使用if语句:

  bool value = true;

  if(value)
  {
      return new Test1StandardChargeCalculator();
  }

  return new Test2StandardChargeCalculator();
Run Code Online (Sandbox Code Playgroud)

  • @ m.edmondson - 近视?对booleans进行切换看起来像程序员错误.我会说编译器在这里做正确的事情.你当然只能有一个`case`和一个`default` - 它也应该排除错误(但是`switch`与单个`case`看起来有多么愚蠢?). (4认同)