[英]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.