我正在研究一种应遵循这一逻辑的方法:
这就是我所拥有的:
static int GetPlayers()
{
int players = 0;
Console.Write("How many people are playing?");
try
{
players = Convert.ToInt16(Console.ReadLine());
}
catch (Exception e)
{
Console.Write(e.Message + "\n" +
"----------");
GetPlayers();
}
return players;
}
问题很简单,“并非所有代码路径都返回一个值。”我可以让它做我想做的事,但它会有一些丑陋的条件陈述反映出我是多少业余爱好者。我正在寻找一个优雅的专业级解决方案,以帮助我学习如何在将来正确处理这种类型的逻辑序列。
提前谢谢!
答案 0 :(得分:1)
您必须return
第二次调用该方法的结果。如果您只是在不返回值的情况下调用方法,则结果将为0
(如果已发生错误)。
您也可以players = GetPlayers()
我认为它更优雅,因为该方法只有一条出路。
static int GetPlayers()
{
int players = 0;
Console.Write("How many people are playing?");
try
{
players = Convert.ToInt16(Console.ReadLine());
}
catch (Exception e)
{
Console.Write(e.Message + "\n" +
"----------");
return GetPlayers(); // return the result
}
return players;
}
用法看起来像这样:
static void Main(string[] args)
{
var players = GetPlayers();
Console.WriteLine("Players count: " + players);
Console.ReadLine();
}
输出如下:
How many people are playing?s
Input string was not in a correct format.
----------How many people are playing?9
Players count: 9
答案 1 :(得分:1)
您可以使用while循环,只有在玩家设置正确后才会返回。
static int GetPlayers()
{
int? players;
Console.Write("How many people are playing?");
while (players == null)
{
try
{
players = Convert.ToInt16(Console.ReadLine());
}
catch (Exception e)
{
Console.Write(e.Message + "\n" + "----------");
}
}
return players.Value;
}
答案 2 :(得分:1)
异常代码路径没有返回值,编译器注意到了这一点。这是一个bug,当你捕获异常时从来都不常见。你通常不会认为用户输入错误有什么特别之处。此外,它不是你唯一应该检查的东西,你也不会对-1或3000名玩家感到高兴。
只需创建一个无限循环,当您输入正确的条目时就可以逃脱。像这样:
static int GetPlayers(int max = 10) {
for (;;) {
Console.Write("Number of players: ");
int players;
if (int.TryParse(Console.ReadLine(), out players)) {
if (players > 0 && players <= max) return players;
}
Console.WriteLine(" Oops, please type a number between 1 and " + max.ToString());
}
}
有些程序员发现for (;;)
光栅,我不是其中之一。如果你讨厌,你可以使用while (true)
。