'并非所有代码路径都返回一个值'使用switch语句

时间:2014-12-09 10:13:43

标签: c# .net string

我正在尝试编写我的第一个程序,它的目的是成为一个聊天模拟器,但我收到的错误是: 错误1'Chat_Simulator.Program.UserConnection()':并非所有代码路径都返回值

以下是代码:

        string NUsername = UserConnection();
        Console.WriteLine("You have connected to:" + NUsername);


    static String UserConnection()
    {
        Console.WriteLine("Connecting to random user...");
        Thread.Sleep(2000);
        Console.Clear();
        Random random = new Random();
        //picks random user
        switch (random.Next(4))
        {
            case 0:
                {
                    Console.WriteLine("Connecting you to Jerry");
                    string Cusername = "Jerry";
                    return Cusername;
                    //not sure if this works?
                }
            case 1:
                {
                    Console.WriteLine("Connecting you to Stinger8");
                    string Cusername = "Stinger8";
                    return Cusername;
                }
            case 2:
                {
                    Console.WriteLine("Connecting you to MadamThus");
                    string Cusername = "Madamthus";
                    return Cusername;
                }
            case 3:
                {
                    Console.WriteLine("Connecting you to Kawai49");
                    string Cusername = "Kawai49";
                    return Cusername;
                }
        }

1 个答案:

答案 0 :(得分:1)

编译器不知道switch内的值不能超过3或小于0.

因此,您必须告诉编译器在它所处的情况下该怎么做。最简单的方法是向default添加switch子句。我更喜欢Exception而不是返回默认值,因为它清楚地表明实际出现了问题:

case 3:
{
    ...
}
default:
{
    throw new Exception("I totally didn't expect this.");
}