C# enumeration (enum), constant (const) and readonly

Const is a (class) static constant whose value is determined during compilation. Readonly is a dynamic constant.

A. The difference between const and readonly in C#

     There are two ways to define constants in C#. One is called static constants, which are defined using the "const" keyword (ie const = static const). The value defined by const is determined during compilation and can only be declared through constant expressions. Specify its value. The other is called dynamic constants, which are defined with the "readonly" keyword. The difference between the two is as follows:

1. const can only modify primitive types, enumeration types or string types, that is, the const type must belong to the value type range, and its value cannot be set by new, and readonly has no restrictions;
2. const It can be used to modify the field of a class or a local variable; and readonly is only used to modify the field of a class;
3. const constants belong to the class level rather than the instance object level, and readonly constants can be either class level or instance object level;
4. const constants are more efficient and do not occupy memory space. After the const constant is compiled by the compiler, the place where the const variable is referenced in the code will be replaced by the actual value corresponding to the const variable. And readonly constants require the system to allocate space for the constants it defines.

 

 

B. Analysis of the difference between the application of C# enumeration and constant, the original address: http://developer.51cto.com/art/200908/144474.htm

What is the difference between C# enumeration and constant application?

When we need to define, we prefer enumeration.

In C#, the real power of enums is that behind the scenes they are instantiated as structs derived from the base class System.Enum. This means that methods can be called on them to perform useful tasks. Note that because of the way the .NET Framework is implemented, there is no performance penalty for syntactically treating enums as structs. In fact, once the code is compiled, enums become primitive types, similar to int and float.

But in practical applications, you may find that we often define enumeration types in English, because development tools are originally developed in English, and Americans can directly understand the meaning of enumeration types when they use them. In fact, we have one more step during development, and we need to translate the enumeration type. No way, who made the programming language written in English, if it is written in Chinese, then we don't need to translate, and it becomes very convenient to use enumeration. To give a simple example, when TimeOfDay.Morning sees Morning, Americans know it is morning, but for Chinese users, many people may not understand it, which requires us to translate and explain, and then go up The method of getTimeOfDay() above is actually doing the translation work. Therefore, when using enumeration, it is not very convenient. Sometimes we are more willing to create constants, and then declare a collection in the class to hold the constants and their meanings.

C# enumerations and constants using constant definition: This method is feasible, but there is no guarantee that the incoming parameter day is actually limited.

  1. using System;  
  2. using System.Collections.Generic;  
  3.  //C# enumeration and constant application difference
  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. /// Get the day of the week  
  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,  "Evening");  
  23. }  
  24.  
  25. return list[time];  
  26. }  

Hopefully we can find a better way to turn the enumeration into the collection we want. After searching for a long time, I finally found some clues. Through reflection, a description for an enumeration type is obtained.

Add a description to the definition of the enum that distinguishes between C# enums and constants

  1. using System;  
  2. using System.ComponentModel;  
  3.  //C# enumeration and constant application difference
  4. public enum TimeOfDay  
  5. {  
  6. [Description( "AM")]  
  7. Moning,  
  8. [Description( "afternoon")]  
  9. Afternoon,  
  10. [Description( "Night")]  
  11. Evening,  
  12. }; 

The difference between C# enumeration and constant application is to get the value and express the key-value pair

  1. /// ﹤summary﹥  
  2. /// Read and return a key-value pair from the enumeration type and its properties  
  3. /// ﹤/summary﹥  
  4. /// ﹤param name="enumType"﹥  
  5. Type, the format of this parameter is typeof (the enumeration type that needs to be read)  
  6. ﹤/param﹥  
  7. /// ﹤returns﹥ key-value pair ﹤/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# enumeration and constant application difference
  39. return nvc;  

Of course, the definition of the enumeration can also be in Chinese, which is very simple to solve the above problem, but our code does not seem to be a unified language.

  1. ChineseEnum  
  2. public enum TimeOfDay  
  3. {  
  4. morning,  
  5. afternoon,  
  6. night,  

C, C# get the key name, value and description of the enumeration, traverse the enumeration

Operations on C# Enum enumerations. key names, values ​​and descriptions and traverse enums

 

 /// <summary>

     /// Promotions
     /// </summary>
     public enum cxsd
     {




         [Description("Recommended")]
         tj = 2,
         [Description("Top")]
         zd = 4,
         [Description("Hot Sale")]
         rm = 8

     }

 

//get enumeration value

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

 

//get enumeration name

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

get enum description

descriptions(cxsd.rm);//Call

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

// loop through the enumeration

 

 

  Type type = typeof(cxsd);


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

 

 

// Extend a generic method by the above method. to get a description of the specified value

 

// call the method

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

   

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325072964&siteId=291194637