c# - 并非所有代码路径都返回一个值 - 枚举实践

标签 c# enums return

我试图执行一个简单的代码来研究枚举主题。 然而,我遇到了这个问题:“并非所有代码路径都返回一个值”。 这是代码:

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/

相关文章:

c# - 如何从枚举类型的名称和 int 中获取枚举名称

java - java中什么时候使用枚举?

ruby - 在 Ruby block 中使用 'return'

c# - 为什么 javascript 会忽略文本框默认文本的更改?

c# - 好的类设计实例

c# - 如何改进我的日志类

Swift:泛型中的嵌套枚举适用于所有类型?

c# - VB.NET 执行顺序

c++ - const T * search ( const T &) 返回无效

c# - 包含 WP8 的 PCL 项目中的 Azure 移动服务