C# 枚舉和常量應(yīng)用區(qū)別淺析
C# 枚舉和常量應(yīng)用區(qū)別是什么呢?
當(dāng)我們需要定義的時(shí)候呢,優(yōu)先考慮枚舉。
在C#中,枚舉的真正強(qiáng)大之處是它們在后臺會實(shí)例化為派生于基類System.Enum的結(jié)構(gòu)。這表示可以對它們調(diào)用方法,執(zhí)行有用的任務(wù)。注意因?yàn)?NET Framework的執(zhí)行方式,在語法上把枚舉當(dāng)做結(jié)構(gòu)是不會有性能損失的。實(shí)際上,一旦代碼編譯好,枚舉就成為基本類型,與int和float類似。
但是在實(shí)際應(yīng)用中,你也許會發(fā)現(xiàn),我們經(jīng)常用英語定義枚舉類型,因?yàn)殚_發(fā)工具本來就是英文開發(fā)的,美國人用起來,就直接能夠明白枚舉類型的含義。其實(shí),我們在開發(fā)的時(shí)候就多了一步操作,需要對枚舉類型進(jìn)行翻譯。沒辦法,誰讓編程語言是英語寫的,如果是漢語寫的,那我們也就不用翻譯了,用起枚舉變得很方便了。舉個(gè)簡單的例子,TimeOfDay.Morning一看到Morning,美國人就知道是上午,但是對于中國的使用者來說,可能有很多人就看不懂,這就需要我們進(jìn)行翻譯、解釋,就向上面的getTimeOfDay()的方法,其實(shí)就是做了翻譯工作。所以,在使用枚舉的時(shí)候,感覺到并不是很方便,有的時(shí)候我們還是比較樂意創(chuàng)建常量,然后在類中,聲明一個(gè)集合來容納常量和其意義。
C# 枚舉和常量之使用常量定義:這種方法固然可行,但是不能保證傳入的參數(shù)day就是實(shí)際限定的。
- using System;
- using System.Collections.Generic;
- //C# 枚舉和常量應(yīng)用區(qū)別
- 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];
- }
- }
希望能夠找到一種比較好的方法,將枚舉轉(zhuǎn)為我們想要的集合。搜尋了半天終于找到了一些線索。通過反射,得到針對某一枚舉類型的描述。
C# 枚舉和常量應(yīng)用區(qū)別之枚舉的定義中加入描述
- using System;
- using System.ComponentModel;
- //C# 枚舉和常量應(yīng)用區(qū)別
- public enum TimeOfDay
- {
- [Description("上午")]
- Moning,
- [Description("下午")]
- Afternoon,
- [Description("晚上")]
- Evening,
- };
C# 枚舉和常量應(yīng)用區(qū)別之獲得值和表述的鍵值對
- /// ﹤summary﹥
- /// 從枚舉類型和它的特性讀出并返回一個(gè)鍵值對
- /// ﹤/summary﹥
- /// ﹤param name="enumType"﹥
- Type,該參數(shù)的格式為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# 枚舉和常量應(yīng)用區(qū)別
- return nvc;
- }
當(dāng)然,枚舉定義的也可以是中文,很簡單的解決的上面的問題,但是,我們的代碼看起來就不是統(tǒng)一的語言了。
- ChineseEnum
- public enum TimeOfDay
- {
- 上午,
- 下午,
- 晚上,
- }
C# 枚舉和常量應(yīng)用區(qū)別的基本情況就向你介紹到這里,希望對你了解和學(xué)習(xí)C# 枚舉有所幫助。
【編輯推薦】