[英]C# Static vs enum for readonly variables
例如,假设您有以下课程:
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;
}
}
不要害怕创建自定义类型。
你可以用这样的东西:
// 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;
}
}
并像枚举一样使用这种类型,但它更强大(不再需要开关):
// 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();
这种类型的数据使用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;
}
如果要进行枚举,请使用枚举结构。 如果您希望从属于特定类的代码中的任何位置访问值,请使用静态。
但是如果你想要的只是一个不能改变的值,你可以考虑使用“const”。
正如 dav_i 所评论的,在这种情况下,您最好使用枚举。
Enum
就像一个数值的别名。 因此,如果您想在问题中使用strings
,那么枚举对您来说不是正确的选择。
要从枚举中获取名称,您必须使用Reflection
,而 Reflection 并不是最快的方法。
我想使用enum
更好,因为标志的数据类型是字符串还是整数都无关紧要。 enums
也是将标志组合在一起的一种非常有意义的完整方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.