【问题标题】:All paths don't return a value所有路径都不返回值
【发布时间】:2020-03-16 15:10:29
【问题描述】:

我不确定我的代码到底出了什么问题,因为它以前可以工作,但现在它向我显示了这个错误。

main.cs(179,20): 错误 CS0161: `CarProgram.ChangeGears(int, string)': 并非所有代码路径都返回值

该程序用于汽车功能,在某种程度上就像一个模拟器,但我想在继续处理其他错误之前解决第一个错误。

这是代码

private static int ChangeGears(int s, string g)
{
     Console.WriteLine("Inside the function Change Gears");
     if (s == 0)
     {
      string haveGear;
     Console.WriteLine("What gear would you like to have?");
     haveGear = Console.ReadLine();
     haveGear = haveGear.ToUpper();
     if (haveGear == "P" || haveGear == "R" || haveGear == "N" || haveGear == "D")
        {
            switch (haveGear)
            {
                case "P":
                {
                    Console.WriteLine("You are in park");
                    break;
                }

                case "N":
                {
                    Console.WriteLine("You are in neutral");
                    break;
                }

                case "D":
                {
                    Console.WriteLine("You are in drive");
                    break;
                }

                case "R":
                {
                    Console.WriteLine("You are in reverse");
                    break;
                }
            }//close
            g = haveGear;
        }
     else
     {
         Console.WriteLine("The speed must be 0 to change gears.");
     }
     Console.WriteLine("Gear is "+ g);

     return 0;
}
}// close ChangeGears

【问题讨论】:

  • 如果“s”不等于零,则没有返回值。

标签: c# compiler-errors valueerror


【解决方案1】:

格式化你的日常生活,

private static int ChangeGears(int s, string g) {
  Console.WriteLine("Inside the function Change Gears");

  if (s == 0) {
    ...
    /* Some logic here */
    ... 
    return 0; // <- when s == 0 ChangeGears returns 0
  }

  //TODO: return value when s != 0
}// close ChangeGears

清楚地看到ChangeGears 没有返回任何东西s != 0

【讨论】:

    【解决方案2】:

    在 ChangeGears 方法中:

    你是说:

    if(condition)
    {
      // Do Stuff
      return 0;
    }
    // Here is implicitly:
    if (not Condition)
    {
      //Do nothing
    }
    

    else 也需要返回。

    此外,错误消息还会为您提供所需的信息。

    main.cs(179,20):错误 CS0161

    是说第 179 行是有问题的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多