C# 只读变量的静态与枚举

Mar*_*sen 1 c# enums static

假设您有以下课程:

    public static class TimeType
{
    public static String DAY = "Day";
    public static String WEEK = "week";
    public static String MONTH = "month";
    public static String YEAR = "year";
}
Run Code Online (Sandbox Code Playgroud)

现在,在编程时您将能够访问或这些变量。

我的问题是让它们作为一个会更好吗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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

slo*_*oth 5

不要害怕创建自定义类型。

你可以这样做:

// omitted error-/equality checking for brevity
public sealed class TimeType
{
    private static Dictionary<string, TimeType> _dic = new Dictionary<string, TimeType>();

    public static TimeType DAY   = new TimeType("Day", DateTimeIntervalType.Days);
    public static TimeType WEEK  = new TimeType("week", DateTimeIntervalType.Weeks);
    public static TimeType MONTH = new TimeType("month", DateTimeIntervalType.Months);
    public static TimeType YEAR  = new TimeType("year", DateTimeIntervalType.Years);

    public string Name { get; private set; }
    public DateTimeIntervalType Type { get; private set; }

    private TimeType(string name, DateTimeIntervalType type)
    {
        Name = name;
        Type = type;
        _dic[name] = this;
    }

    public static TimeType GetByName(string name)
    {
        return _dic[name];
    }

    public static IEnumerable<TimeType> All()
    {
        return _dic.Values;
    }
}
Run Code Online (Sandbox Code Playgroud)

并像枚举一样使用这种类型,但它更强大(不再需要开关):

// looks like a enum
var day = TimeType.DAY;

// Get the DateTimeIntervalType directly
DateTimeIntervalType day_interval = day.Type;

// Get the correct TimeType by a string
var month = TimeType.GetByName("Day");

// Get all TimeTypes
var allTypes = TimeType.All();
Run Code Online (Sandbox Code Playgroud)