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();        }

相关文章
相关标签/搜索