C#构建代码出现not all code paths return a value错误

来源:互联网 发布:淘宝dsr公式 编辑:程序博客网 时间:2024/06/01 08:47

这句话的翻译是:不是所有代码都会返回value值

例如下段代码:

        static string getage(int age) {
            if (age >= 0 && age <= 3) {
                return "婴幼儿";
            }
            else if (age>3&&age<=18){
                return "青少年";
            }
            else if (age < 0) {
                throw new Exception("数据错误");
            }
      }

这段代码不能保证一定能够执行到if和else if,若既不符合if条件,也不符合else if条件,则无返回值;故在代码最后加上else即可解决;


阅读全文
2 0