我正在尝试开发一种方法来检查用户输入,如果它通过验证,则只返回输入。
这就是我想要做的:
- 用户输入输入
- 检查输入值
- 如果输入满足逻辑,则返回该值,否则再次调用该函数。
这确实是我想要的,但编译器指出not all code paths return a value
:
public static int UserInput(){
int input = int.Parse(Console.ReadLine());
if (input < 1 || input > 4){
Console.Write("Invalid Selection. Enter a valid Number (1,2,3 or 4): ");
if (input < 1 || input > 4) UserInput();
} else{
return input;
}
}
但是,这是满足编译器的以下代码。
public static int UserInput()
{
int input = int.Parse(Console.ReadLine());
if (input < 1 || input > 4)
{
Console.Write("Invalid Selection. Enter a valid Number (1,2,3 or 4): ");
if (input < 1 || input > 4)
{
UserInput();
return -1; // Never reached, but must be put in to satisfy syntax of C#
}
return input; // Never reached, but must be put in to satisfy syntax of C#
}
else
{
return input;
}
}
这种工作,但我得到奇怪的结果。如果用户在input
第一次输入时输入 1、2、3 或 4(即if
语句计算为false
),则返回的输入就是用户输入的任何内容。但是,如果用户要输入一个不是1、2、3 或 4的值,然后输入一个有效数字,那么程序将执行以下操作:
- 返回输入;
- 跳转到子 if 语句并运行 UserInput();
- 然后返回-1。