我试图执行一个简单的代码只是为了研究枚举主题.然而,我遇到了这个问题:"并非所有代码路径都返回一个值".这是代码:
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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道什么可能导致这个问题.谢谢 :)
你应该处理这个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");
}
}
Run Code Online (Sandbox Code Playgroud)
所以,如果你打电话
WhichSeason(13); //throws exception
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |