C# 枚舉和常量應用區別淺析
C# 枚舉和常量應用區別是什么呢?
當我們需要定義的時候呢,優先考慮枚舉。
在C#中,枚舉的真正強大之處是它們在后臺會實例化為派生于基類System.Enum的結構。這表示可以對它們調用方法,執行有用的任務。注意因為.NET Framework的執行方式,在語法上把枚舉當做結構是不會有性能損失的。實際上,一旦代碼編譯好,枚舉就成為基本類型,與int和float類似。
但是在實際應用中,你也許會發現,我們經常用英語定義枚舉類型,因為開發工具本來就是英文開發的,美國人用起來,就直接能夠明白枚舉類型的含義。其實,我們在開發的時候就多了一步操作,需要對枚舉類型進行翻譯。沒辦法,誰讓編程語言是英語寫的,如果是漢語寫的,那我們也就不用翻譯了,用起枚舉變得很方便了。舉個簡單的例子,TimeOfDay.Morning一看到Morning,美國人就知道是上午,但是對于中國的使用者來說,可能有很多人就看不懂,這就需要我們進行翻譯、解釋,就向上面的getTimeOfDay()的方法,其實就是做了翻譯工作。所以,在使用枚舉的時候,感覺到并不是很方便,有的時候我們還是比較樂意創建常量,然后在類中,聲明一個集合來容納常量和其意義。
C# 枚舉和常量之使用常量定義:這種方法固然可行,但是不能保證傳入的參數day就是實際限定的。
- using System;
- using System.Collections.Generic;
- //C# 枚舉和常量應用區別
- public class TimesOfDay
- {
- public const int Morning = 0;
- public const int Afternoon = 1;
- public const int Evening = 2;
- public static Dictionary﹤int, string﹥ list;
- /// ﹤summary﹥
- /// 獲得星期幾
- /// ﹤/summary﹥
- /// ﹤param name="day"﹥﹤/param﹥
- /// ﹤returns﹥﹤/returns﹥
- public static string getTimeNameOfDay(int time)
- {
- if (list == null || list.Count ﹤= 0)
- {
- list = new Dictionary﹤int, string﹥();
- list.Add(Morning, "上午");
- list.Add(Afternoon, "下午");
- list.Add(Evening, "晚上");
- }
- return list[time];
- }
- }
希望能夠找到一種比較好的方法,將枚舉轉為我們想要的集合。搜尋了半天終于找到了一些線索。通過反射,得到針對某一枚舉類型的描述。
C# 枚舉和常量應用區別之枚舉的定義中加入描述
- using System;
- using System.ComponentModel;
- //C# 枚舉和常量應用區別
- public enum TimeOfDay
- {
- [Description("上午")]
- Moning,
- [Description("下午")]
- Afternoon,
- [Description("晚上")]
- Evening,
- };
C# 枚舉和常量應用區別之獲得值和表述的鍵值對
- /// ﹤summary﹥
- /// 從枚舉類型和它的特性讀出并返回一個鍵值對
- /// ﹤/summary﹥
- /// ﹤param name="enumType"﹥
- Type,該參數的格式為typeof(需要讀的枚舉類型)
- ﹤/param﹥
- /// ﹤returns﹥鍵值對﹤/returns﹥
- public static NameValueCollection
- GetNVCFromEnumValue(Type enumType)
- {
- NameValueCollection nvc = new NameValueCollection();
- Type typeDescription = typeof(DescriptionAttribute);
- System.Reflection.FieldInfo[]
- fields = enumType.GetFields();
- string strText = string.Empty;
- string strValue = string.Empty;
- foreach (FieldInfo field in fields)
- {
- if (field.FieldType.IsEnum)
- {
- strValue = ((int)enumType.InvokeMember(
- field.Name, BindingFlags.GetField, null,
- null, null)).ToString();
- object[] arr = field.GetCustomAttributes(
- typeDescription, true);
- if (arr.Length ﹥ 0)
- {
- DescriptionAttribute aa =
- (DescriptionAttribute)arr[0];
- strText = aa.Description;
- }
- else
- {
- strText = field.Name;
- }
- nvc.Add(strText, strValue);
- }
- } //C# 枚舉和常量應用區別
- return nvc;
- }
當然,枚舉定義的也可以是中文,很簡單的解決的上面的問題,但是,我們的代碼看起來就不是統一的語言了。
- ChineseEnum
- public enum TimeOfDay
- {
- 上午,
- 下午,
- 晚上,
- }
C# 枚舉和常量應用區別的基本情況就向你介紹到這里,希望對你了解和學習C# 枚舉有所幫助。
【編輯推薦】