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# 枚举和常量应用区别是什么呢?

当我们需要定义的时候呢,优先考虑枚举。

在C#中,枚举的真正强大之处是它们在后台会实例化为派生于基类System.Enum的结构。这表示可以对它们调用方法,执行有用的任务。注意因为.NET Framework的执行方式,在语法上把枚举当做结构是不会有性能损失的。实际上,一旦代码编译好,枚举就成为基本类型,与int和float类似。

但是在实际应用中,你也许会发现,我们经常用英语定义枚举类型,因为开发工具本来就是英文开发的,美国人用起来,就直接能够明白枚举类型的含义。其实,我们在开发的时候就多了一步操作,需要对枚举类型进行翻译。没办法,谁让编程语言是英语写的,如果是汉语写的,那我们也就不用翻译了,用起枚举变得很方便了。举个简单的例子,TimeOfDay.Morning一看到Morning,美国人就知道是上午,但是对于中国的使用者来说,可能有很多人就看不懂,这就需要我们进行翻译、解释,就向上面的getTimeOfDay()的方法,其实就是做了翻译工作。所以,在使用枚举的时候,感觉到并不是很方便,有的时候我们还是比较乐意创建常量,然后在类中,声明一个集合来容纳常量和其意义。

C# 枚举和常量之使用常量定义:这种方法固然可行,但是不能保证传入的参数day就是实际限定的。

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

   

 

猜你喜欢

转载自www.cnblogs.com/cheng2015/p/8975623.html