C#Static vs enum用于只读变量

时间:2014-04-15 12:09:04

标签: c# static enums

比如说你有以下课程:

    public static class TimeType
{
    public static String DAY = "Day";
    public static String WEEK = "week";
    public static String MONTH = "month";
    public static String YEAR = "year";
}

现在编程时你可以访问或者这些变量。

我的问题是将它们作为Enum

会更好吗?

我想使用这些变量的方式如下:

    private DateTimeIntervalType GetIntervalType()
    {

        switch (TimeType)
        {
            case "week":
                return DateTimeIntervalType.Weeks;
            case "month":
                return DateTimeIntervalType.Months;
            case "year":
                return DateTimeIntervalType.Years;
            default:
                return DateTimeIntervalType.Days;
        }
    }

3 个答案:

答案 0 :(得分:2)

这种类型的数据使用enum是有意义的。我会通过以下方式构建您的enum

public enum DateTimeIntervalType
{
    None = 0, // this is a sensible default so you always have to define which
    Days = 1,
    Weeks = 2, // all are numbered so any changes don't rely on order of enum
    Months = 3,
    Years = 4
}

然后您可以使用:

代替您的switch语句
var interval = (DateTimeIntervalType)Enum.Parse(
                    typeof(DateTimeIntervalType), 
                    text);

然后您可以像往常一样使用enum

if (someEnumValue == DateTimeIntervalType.Weeks)
{
    // do something
}

switch(someEnumValue)
{
    case DateTimeIntervalType.Days:
        // something
        break;
    case DateTimeIntervalType.Weeks:
        // something
        break;
}

答案 1 :(得分:1)

Enum就像数字值的别名。 因此,如果您想在问题中使用strings,那么枚举对您来说不是正确的。

要从枚举中获取名称,您必须使用Reflection,而反射并不是最快的方法。

答案 2 :(得分:1)

我想使用enum会更好,因为如果它是字符串或整数,那么标志的数据类型无关紧要。同样enums是将标志组合在一起的非常有意义的完整方式。