C # enumerations (enum), constants (const), and ReadOnly

Source: Internet
Author: User

The const modifier is a (class) static constant, whose value is a dynamic constant that is determined during compilation by the ReadOnly adornment.

A, the difference between Const and readonly in C #

There are two ways to define constants in C #, a static constant, defined with the "const" keyword (that is, const = static const), a const-defined value is determined during compilation, and its value can be specified only at declaration time through a constant expression. The other is called Dynamic constants, which are defined by the "readonly" keyword. The two differences are as follows:

1. Const can only modify primitive type, enum type, or string type, that is, restrict const type to be of value type range, and its value cannot be set by new, ReadOnly no Limit;
2. Const can be used to modify class field or a local variable (local variable), while ReadOnly is only used to modify class field;
3. Const constants belong to the class level, not the instance object level, and the ReadOnly constant can be either a class level or an instance object level;
4. Const constants are more efficient and do not occupy memory space. Const constants are compiled by the compiler, where the const variable is referenced in code in place of the actual value corresponding to the const variable. The ReadOnly constant requires the system to allocate space for the constants it defines.

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

What are the differences between C # enumerations and constant applications?

When we need to define it, the enumeration is given precedence.

In C #, the real power of enumerations is that they are instantiated in the background as a struct that derives from the base class System.Enum. This means that you can invoke methods on them and perform useful tasks. Note that because of the way the. NET framework is executed, there is no performance penalty for the syntax of enumerating enumerations as structs. In fact, once the code is compiled, the enumeration becomes the base type, similar to int and float.

But in practical applications, you might find that we often define enumeration types in English, because development tools are developed in English, and Americans use them to understand the meaning of enumerated types directly. In fact, we have one more step in the development, we need to translate the enumeration type. No way, who let the programming language is written in English, if it is written in Chinese, then we do not have to translate, with the enumeration became very convenient. To give a simple example, timeofday.morning see morning, Americans know is the morning, but for Chinese users, there may be many people can not understand, which requires us to translate, explain, to the above the Gettimeofday () method, is actually doing translation work. Therefore, when using enumerations, it is not very convenient to feel, sometimes we are more willing to create constants, and then in the class, declare a collection to accommodate the constant and its meaning.

C # enumerations and constants are defined using constants: Although this method is feasible, it is not guaranteed that the passed-in Parameters day is actually qualified.

  1. Using System;
  2. Using System.Collections.Generic;
  3. C # Enumerations and constants application differences
  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, "Morning");
  21. List.  Add (afternoon, "PM");
  22. List.  ADD (Evening, "Night");
  23. }
  24. return List[time];
  25. }
  26. }

Hopefully we can find a better way to convert the enumeration to the set we want. Search for half a day finally found some clues. A description of an enumeration type is obtained by reflection.

C # Enumerations and constants apply a description to the definition of the enumeration that applies the difference

    1. Using System;
    2. Using System.ComponentModel;
    3. C # Enumerations and constants application differences
    4. Public enum TimeOfDay
    5. {
    6. [Description ("Morning")]
    7. Moning,
    8. [Description ("Afternoon")]
    9. Afternoon,
    10. [Description ("Night")]
    11. Evening,
    12. };

C # Enumerations and constants apply the difference between the obtained value and the stated key-value pair

  1. ﹤summary﹥
  2. Reads from the enumeration type and its attributes and returns a key-value pair
  3. ﹤/summary﹥
  4. ﹤param name= "Enumtype" ﹥
  5. Type, the format of the parameter is typeof (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 constants apply differences
  39. return NVC;
  40. }

Of course, the enumeration definition can also be Chinese, very simple to solve the above problem, but our code does not look like a unified language.

    1. Chineseenum
    2. Public enum TimeOfDay
    3. {
    4. Morning
    5. Afternoon
    6. At night
    7. }

C, C # gets the key name, value, and description of the enumeration, iterating through the enumeration

The operation of the C # Enum enumeration. Key names, values and descriptions, and traversal enumerations

<summary>

Promotion
</summary>
public enum Cxsd
{




[Description ("recommended")]
TJ = 2,
[Description ("pinned")]
ZD = 4,
[Description ("Hot sale")]
RM = 8

}

Get enumeration values

Array Rolearry = Enum.getvalues (typeof (Cxsd));

Get enumeration Name

String[]rolearry = Enum.getnames (typeof (Cxsd));

Get enumeration Description

Descriptions (cxsd.rm);//Call

    public static string description (enum  en)
        {


  &NBSP ;         Type type = en. GetType ();
            memberinfo[] Meminfo = type. GetMember (en. ToString ());
            if (meminfo! = null && meminfo.length > 0)
    &NBSP ;       {
                object[] attrs = meminfo[0]. GetCustomAttributes (typeof (System.ComponentModel.DescriptionAttribute), false);
                if (attrs! = null && attrs. Length > 0)
                    return ((DescriptionAttribute) attr S[0]). Description;
           }
            return en. ToString ();
       }

Traversal enumeration

  Type type = typeof (Cxsd);            foreach (FieldInfo x in type. GetFields (BindingFlags.Public | bindingflags.static)            {                cxsd item = (cxsd) x.getvalue (null);            }

Extend a common method with the above method. To get the descriptive information for the specified value

Calling methods

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

Vlist.add (4);

Vlist.add (8);

Descriptions<cxsd> (Vlist);

<summary>
Get description Information
</summary>
<param name= "Envalue" > Collection of enumeration values </param>
<returns> enumeration values corresponding to the description collection </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 ();
}

C # enumerations (enum), constants (const), and ReadOnly

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.