【问题标题】:c# public static string, not all code paths return a valuec# public static string,并非所有代码路径都返回值
【发布时间】:2016-06-01 12:39:48
【问题描述】:

我还没有完全理解方法,我不知道为什么会发生这种情况......我试图让我的代码更改为单词,我认为这是要走的路。

namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {
            Random r = new Random();
            Console.WriteLine("Hi wanna play rock paper scissors?<press enter to continue>");
            Console.ReadKey();
            int user = 0;
            int ai = r.Next(1, 4);
            Console.WriteLine("Pick what youll show! (1-rock, 2-paper, 3-scissors) and press enter");
            user = Convert.ToInt32(Console.ReadLine());
            if (user > 3)
            {
                Console.WriteLine("ERROR! your number must be <= 3. <Press enter to close the program>");
                goto end;
            }
            if (user == ai)
            {
                Console.WriteLine("Its a draw! <press enter to continue>");
                goto end;
            }


            Console.WriteLine(user);

end:
Console.ReadKey();
        }
        public static string ntw (int user) //ntw: not all code paths return a value
    {
        if (user == 1)
            return "rock";
        if (user == 2)
            return "paper";
        if (user == 3)
            return "scissors";

    }
    }
}

提前致谢。

【问题讨论】:

  • 如果user 不是 1、2 或 3 怎么办?
  • 1.请不要使用goto。 2 发布代码时,请仔细检查缩进的一致性和可读性。
  • 你真的应该使用Dictionary 来处理这种事情。

标签: c# string return


【解决方案1】:

你的方法的返回类型是string。这意味着你的方法应该总是返回一些字符串值。在您当前的实现中,当用户变量的值为1 或2 或3 时,它会返回一些字符串。如果您使用值 25 调用此方法怎么办?编译器不知道怎么办!

如果用户值不是1 或2 或3,您的方法应该返回一些字符串

public static string ntw (int user)
{
     if (user == 1)
        return "rock";
     if (user == 2)
         return "paper";
     if (user == 3)
         return "scissors";

     return string.empty; // Here i am returning an empty string.
}

【讨论】:

  • 或者返回 string.empty :)。
【解决方案2】:

你也可以使用 switch 语句,在这种情况下,如果用户不是 1、2 或 3,默认情况下会给你一个 Null 或一个空字符串 :)

    public static string ntw (int user)
    {
        switch (user)
        {
            case 1:
                return "rock";
            case 2:
                return "paper";
            case 3:
                return "scissors";
            default:
                return null; // or return string.Empty
        }
    }

【讨论】:

    【解决方案3】:

    如果值必须在 1..3 范围内(并且返回 string.Empty 字符串没有意义),那么您可以这样写:

    public static string ntw (int user) 
    {
        if (user == 1)
            return "rock";
        if (user == 2)
            return "paper";
        if (user == 3)
            return "scissors";
        throw new ArgumentException("Invalid choice");
    }
    

    并在程序的某处处理异常。

    【讨论】:

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