C#枚舉(enum)、常量(const)和readonly

const修飾的是(類)靜態常量,,其值是在編譯期間肯定的readonly修飾的是動態常量。編程

A、C#中的const和readonly的區別編程語言

     C#中定義常量有兩種方式,一種叫作靜態常量,使用「const」關鍵字定義(即const = static const),const定義的值是在編譯期間肯定的,只能在聲明時經過常量表達式指定其值。另外一種叫作動態常量,用「readonly」關鍵字來定義。二者區別以下:

1. const只能修飾基元類型、枚舉類型或字符串類型,即限制const類型必須屬於值類型範圍,且其值不能經過new來進行設置,readonly沒有限制;
2. const可用於修飾class的field或者一個局部變量(local variable);而readonly僅僅用於修飾class的field;
3. const常量屬於類級別而不是實例對象級別,readonly常量既能夠是類級別也能夠是實例對象級別的;
4. const常量的效率更高而且不佔用內存空間。const常量通過編譯器編譯後,在代碼中引用const變量的地方會用const變量所對應的實際值來代替。而readonly常量須要系統爲其所定義的常量分配空間。工具

 

 

B、C#枚舉和常量的應用區別淺析,原文地址:http://developer.51cto.com/art/200908/144474.htm性能

C# 枚舉和常量應用區別是什麼呢?開發工具

當咱們須要定義的時候呢,優先考慮枚舉。spa

在C#中,枚舉的真正強大之處是它們在後臺會實例化爲派生於基類System.Enum的結構。這表示能夠對它們調用方法,執行有用的任務。注意由於.NET Framework的執行方式,在語法上把枚舉當作結構是不會有性能損失的。實際上,一旦代碼編譯好,枚舉就成爲基本類型,與int和float相似。翻譯

可是在實際應用中,你也許會發現,咱們常常用英語定義枚舉類型,由於開發工具原本就是英文開發的,美國人用起來,就直接可以明白枚舉類型的含義。其實,咱們在開發的時候就多了一步操做,須要對枚舉類型進行翻譯。沒辦法,誰讓編程語言是英語寫的,若是是漢語寫的,那咱們也就不用翻譯了,用起枚舉變得很方便了。舉個簡單的例子,TimeOfDay.Morning一看到Morning,美國人就知道是上午,可是對於中國的使用者來講,可能有不少人就看不懂,這就須要咱們進行翻譯、解釋,就向上面的getTimeOfDay()的方法,其實就是作了翻譯工做。因此,在使用枚舉的時候,感受到並非很方便,有的時候咱們仍是比較樂意建立常量,而後在類中,聲明一個集合來容納常量和其意義。code

C# 枚舉和常量之使用常量定義:這種方法當然可行,可是不能保證傳入的參數day就是實際限定的。htm

  1. using System;  
  2. using System.Collections.Generic;  
  3.  //C# 枚舉和常量應用區別
  4. public class TimesOfDay  
  5. {  
  6. public const int Morning = 0;  
  7. public const int Afternoon = 1;  
  8. public const int Evening = 2;  
  9. public static Dictionary﹤int, string﹥ list;  
  10. /// ﹤summary﹥  
  11. /// 得到星期幾  
  12. /// ﹤/summary﹥  
  13. /// ﹤param name="day"﹥﹤/param﹥  
  14. /// ﹤returns﹥﹤/returns﹥  
  15. public static string getTimeNameOfDay(int time)  
  16. {  
  17. if (list == null || list.Count ﹤= 0)  
  18. {  
  19. list = new Dictionary﹤int, string﹥();  
  20. list.Add(Morning, "上午");  
  21. list.Add(Afternoon, "下午");  
  22. list.Add(Evening, "晚上");  
  23. }  
  24.  
  25. return list[time];  
  26. }  

但願可以找到一種比較好的方法,將枚舉轉爲咱們想要的集合。搜尋了半天終於找到了一些線索。經過反射,獲得針對某一枚舉類型的描述。對象

C# 枚舉和常量應用區別之枚舉的定義中加入描述

  1. using System;  
  2. using System.ComponentModel;  
  3.  //C# 枚舉和常量應用區別
  4. public enum TimeOfDay  
  5. {  
  6. [Description("上午")]  
  7. Moning,  
  8. [Description("下午")]  
  9. Afternoon,  
  10. [Description("晚上")]  
  11. Evening,  
  12. }; 

C# 枚舉和常量應用區別之得到值和表述的鍵值對

  1. /// ﹤summary﹥  
  2. /// 從枚舉類型和它的特性讀出並返回一個鍵值對  
  3. /// ﹤/summary﹥  
  4. /// ﹤param name="enumType"﹥  
  5. Type,該參數的格式爲typeof(須要讀的枚舉類型)  
  6. ﹤/param﹥  
  7. /// ﹤returns﹥鍵值對﹤/returns﹥  
  8. public static NameValueCollection   
  9. GetNVCFromEnumValue(Type enumType)  
  10. {  
  11. NameValueCollection nvc = new NameValueCollection();  
  12. Type typeDescription = typeof(DescriptionAttribute);  
  13. System.Reflection.FieldInfo[]   
  14. fields = enumType.GetFields();  
  15. string strText = string.Empty;  
  16. string strValue = string.Empty;  
  17. foreach (FieldInfo field in fields)  
  18. {  
  19. if (field.FieldType.IsEnum)  
  20. {  
  21. strValue = ((int)enumType.InvokeMember(  
  22. field.Name, BindingFlags.GetField, null,   
  23. null, null)).ToString();  
  24. object[] arr = field.GetCustomAttributes(  
  25. typeDescription, true);  
  26. if (arr.Length ﹥ 0)  
  27. {  
  28. DescriptionAttribute aa =   
  29. (DescriptionAttribute)arr[0];  
  30. strText = aa.Description;  
  31. }  
  32. else 
  33. {  
  34. strText = field.Name;  
  35. }  
  36. nvc.Add(strText, strValue);  
  37. }  
  38. }  //C# 枚舉和常量應用區別
  39. return nvc;  

固然,枚舉定義的也能夠是中文,很簡單的解決的上面的問題,可是,咱們的代碼看起來就不是統一的語言了。

  1. ChineseEnum  
  2. public enum TimeOfDay  
  3. {  
  4. 上午,  
  5. 下午,  
  6. 晚上,  

C、C#獲取枚舉的鍵名稱、值和描述,遍歷枚舉

C# Enum  枚舉的操做。  鍵名稱,值 和描述  和 遍歷枚舉

 

 /// <summary>

     /// 促銷
     /// </summary>
     public enum cxsd
     {




         [Description("推薦")]
         tj = 2,
         [Description("置頂")]
         zd = 4,
         [Description("熱賣")]
         rm = 8

     }

 

//獲取 枚舉 值

Array rolearry = Enum.GetValues(typeof(cxsd));

 

//獲取枚舉名稱

String[]rolearry = Enum.GetNames(typeof(cxsd));

獲取枚舉描述

descriptions(cxsd.rm);//調用

    public static string description(Enum  en)
        {


            Type type = en.GetType();
            MemberInfo[] memInfo = type.GetMember(en.ToString());
            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
                if (attrs != null && attrs.Length > 0)
                    return ((DescriptionAttribute)attrs[0]).Description;
            }
            return en.ToString();
        }

//遍歷枚舉

 

 

Type type = typeof(cxsd);


            foreach (FieldInfo x in type.GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                cxsd item = (cxsd)x.GetValue(null);
            }

 

 

//經過以上方法 擴展一個 通用方法 。來獲取  指定值的 描述信息

 

//調用方法

List<int> vlist=new List<int>();

vlist.add(4);

vlist.add(8);

 

descriptions<cxsd>(vlist);

 

 /// <summary>       /// 獲取描述信息       /// </summary>       /// <param name="envalue">枚舉值的集合</param>       /// <returns>枚舉值對應的描述集合</returns>       public static List<String> descriptions<T>(List<int> envalue)       {           Type type = typeof(T);                List<String> deslist = new List<String>();            foreach (FieldInfo x in type.GetFields(BindingFlags.Public | BindingFlags.Static))            {                T item = (T)x.GetValue(null);                if (envalue.Find((int e) => { return e == Convert.ToInt32(item); }) > 0)                {                     deslist.Add(description<T>(item));                 }            }            return deslist;       }         public static string description<T>(T en)        {            Type type = en.GetType();            MemberInfo[] memInfo = type.GetMember(en.ToString());            if (memInfo != null && memInfo.Length > 0)            {                object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);                if (attrs != null && attrs.Length > 0)                    return ((DescriptionAttribute)attrs[0]).Description;            }            return en.ToString();        }

相關文章
相關標籤/搜索