我试图执行一个简单的代码来研究枚举主题。 然而,我遇到了这个问题:“并非所有代码路径都返回一个值”。 这是代码:
namespace ConsoleAppTest
{
class Program
{
enum Seasons { Winter, Spring, Summer, Fall };
static void Main(string[] args)
{
WhichSeason(3);
}
static Seasons WhichSeason(int month)
{
if (month >= 1 || month <= 3)
{
return Seasons.Winter;
}
else if (month >= 4 || month <= 6)
{
return Seasons.Spring;
}
else if (month >= 7 || month <= 9)
{
return Seasons.Summer;
}
else if (month >= 10 || month <= 12)
{
return Seasons.Fall;
}
}
}
}
我想知道是什么导致了这个问题。 谢谢:)
最佳答案
您应该处理 else
案件。你的month
整数也可以是 <1
或 >12
.
static Seasons WhichSeason(int month)
{
if (month >= 1 && month <= 3)
{
return Seasons.Winter;
}
else if (month >= 4 && month <= 6)
{
return Seasons.Spring;
}
else if (month >= 7 && month <= 9)
{
return Seasons.Summer;
}
else if (month >= 10 && month <= 12)
{
return Seasons.Fall;
}
else
{
throw new ArgumentOutOfRangeException("invalid month");
}
}
所以如果你打电话
WhichSeason(13); //throws exception
关于c# - 并非所有代码路径都返回一个值 - 枚举实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46361610/