"并非所有代码路径都返回值"错误

时间:2014-10-06 02:16:28

标签: c#

我试图编辑我的代码以包含方法,但它只是不工作,每次我改变一些东西我得到一个错误代码。这次我的错误代码是"并非所有代码路径都返回一个值"我上面提到的所有变量都是"声明但从未使用" 。我确定我没有正确使用方法,我想知道是否有人可以帮助我。我尝试过研究,但我无法弄明白。

这是我收到错误的地方:

}

public static int Menu()
        {

//Menu for user to select whether to load file or not.
        Console.WriteLine("");
        string input = Console.ReadLine();
        switch (input.ToLower())

        {
        case "yes":
        case "maybe":
            Console.WriteLine("Great!");
            break;
        case "no":
            Console.WriteLine("Too bad!");
            break;
        default:
            Console.WriteLine("I'm sorry, I don't understand that!");
            break;
        }

2 个答案:

答案 0 :(得分:3)

该方法声明它返回int值:

public static int Menu()

但是在方法中没有任何地方可以返回任何东西。如果它不应该返回任何内容,请更改声明以指定:

public static void Menu()

否则,编译器需要确保方法的每次调用都会导致int(或异常,这也是方法的有效退出策略)。这意味着该方法的每个逻辑路径都需要在return语句中终止,该语句提供int值。

答案 1 :(得分:0)

任何时候程序员希望代码返回特定的东西,比如字符串,整数,布尔等,他/她会声明它:

private string Greeting()
{
    string a = "hello"
    string b = "sir"
    return a + " " + b;
}

在这个例子中,你将创建一个名为" Greenting"的新字符串。通过组合a和b的值。为了返回该值,您必须调用" return"并指定输出。

上面我们的私有字符串的输出将是:     你好先生

在你的情况下,你真的不需要任何类型的值来返回,你只想执行一个函数。在这种情况下,您可以指定" void"的返回类型,它允许程序执行函数而无需返回。

以下是我执行菜单选择功能的方法:

private void Menu()
{
    int Selection;  // Will hold selected option
    Console.WriteLine("Please select one of the following options");
    Console.WriteLine("Option 1: Load a file");
    Console.WriteLine("Option 2: Do no load a file");
    Console.WriteLine("______________________________________");
    Console.WriteLine("Please select by entering option 1 or 2");
    Selection = Console.ReadLine();

    switch (Selection)
    {
        case 1:
        Console.WriteLine("Great");
        // Perform whatever function needed to load file
        // by inserting code here
        return;
        case 2:
        Console.WriteLine("Too bad");
        // Perform whatever function needed when no file is loaded
        // by inserting code here
        return;
        default:
        Console.WriteLine("This is an invalid selection");
        // Perform function to redraw the menu and force user to enter a valid selection. 
        // by inserting code here
        return;
    }
}

请记住在代码中调用函数Menu()来生成菜单并执行所需的功能。

这些返回类型最终将成为您的第二天性。我希望这有帮助!

相关问题