C # Enumeration

Source: Internet
Author: User

First, before learning to enumerate, listen to the advantages of enumerations.

1. Enumerations can make the code clearer, allowing the use of descriptive names to represent integer values.

2. Enumeration makes the code easier to maintain, helping to ensure that the variable is given a valid, expected value.

3. Enumerations make code easier to enter.

Second, enumeration description

  1. Simple Enumeration

    • Enumerations are declared using the enum keyword, and are siblings of the class. The enumeration itself can have modifiers, but the members of the enumeration are always public and cannot have access modifiers. Modifiers of the enumeration itself can only use public and internal.
    • Enumerations are value types, implicitly inherited from System.Enum, and cannot be modified manually. The System.Enum itself is a reference type and inherits from System.ValueType.
    • Enumerations are implicitly sealed and are not allowed to derive subclasses as base classes.
    • Enumeration members of enumeration types are static and default to the Int32 type.
    • Each enum member has an associated constant value. The type of this value is the underlying data type of the enumeration. The constant value of each enumeration member must be within the range of the underlying data type of the enumeration. If the underlying data type is not explicitly specified, the default data type is type int.
    • Enumeration members cannot be the same, but the values of enumerations can be the same.
    • Enumerates the comma of the last member and the semicolon following the curly brace to omit

C # provides a class class to facilitate enumeration, and the following is a common way to do this class:

The
method name
CompareTo Compare this instance to a specified object and returns an indication of their relative value
equals Indicates whether this instance equals the specified object
Format
GetName Retrieves the name of the constant with the specified value in the specified enumeration
GetNames retrieves an array of constant names in the specified enumeration
gettypecode   Returns the base of this instance TypeCode
Getunderlyingtype returns the underlying type of the specified enumeration
GetValues cable Specifies an array of constant values in the enumeration
Hasflag Determines whether one or more bit fields are set in the current instance
IsDefined Returns an indication of whether a constant with the specified value exists in the specified enumeration
Parse Converts the string representation of the name or numeric value of one or more enumeration constants to an equivalent enumeration object. A parameter that specifies whether the operation is case-insensitive
TryParse Converts the string representation of the name or numeric value of one or more enumeration constants to an equivalent enumeration object. Return value to indicate whether the conversion succeeded

To display the underlying data type of the specified enumeration is simple, just add a colon when declaring the enumeration, followed by the data type you want to specify.

    Enum Sex:byte//Displays the underlying data type of the specified enumeration    {         male,        female,//This comma can be omitted    };  //This semicolon can be omitted

Explicitly sets the member constant value of the enumeration, which is incremented by default starting at 0. But the following examples are set to 1,2,3,4,5,6,7,0. And the member values can be the same.

    Enum Week    {         Monday = 1,        Tuesday = 2,        Wednesday = 3,        Sunday = 0, Everyday = 1//The value of the member can be set to the same, but  Member not    } Console.WriteLine ((int) week.monday); Get value

Example, gets the enumeration name by the enumeration value and gets the enumeration value by the enumeration name

    Class program    {        static void Main (string[] args)        {            Console.WriteLine (Enum.getname (typeof (Man), 1));  Or Liu Bei (get the name by the value)            string[] array1 = Enum.getnames (typeof (Man));            Console.WriteLine (Array1[1]);   Guan Yu            Array array2 = Enum.getvalues (typeof (Man));            Console.WriteLine (Array2. GetValue (1));  Or Guan Yu            Type t = Enum.getunderlyingtype (typeof (Man));            Console.WriteLine (t);       Output Int32            //get content by value            int i = 1;            String Name = Enum.parse (typeof (Man), i.ToString ()). ToString ();     At this time name= "Liu Bei"            Console.WriteLine (Name);            Gets the content by value            string Name2 = "Guan Yu";            Int J = Convert.ToInt32 (Enum.parse (typeof (Man), Name2));     At this time j=2            Console.WriteLine (j);            Console.readkey ();        }    }    Enum man    {         Liu Bei = 1,        guan Yu = 2,        Zhang Fei = 3    }

  2. Flag Enumeration

Flag enumeration to be declared at the top of the [System.flags] attribute. And the enumeration supports combinatorial operations. Let's start with an example.

    Class program    {        static void Main (string[] args)        {            var man = Week. White | Week. Beauty;  The assignment is 101    calculation method 001 or 100, the result is 101            Console.WriteLine ((int) man);            if ((Man & Week. White) = = Week. White)       //101 man             {                                    //001 white, and                Console.WriteLine ("This person white");      001 If the result is white, you can anti-eject man contains white            }            else            {                Console.WriteLine ("This person black");            }            Console.readkey ();        }    }    [System.flags]    Public enum Week    {         white = 1,  //001        rich = 2,  //010        mei = 4,  //100    }

This bit operation is very useful, and bit operations are also supported in SQL statements. In other words, after the result of an enumeration operation is stored in the database, it can be read according to your requirements. Like what:

Storing a "white beauty" as a database value into the database, then the integer 5 is deposited.

So I would like to read all the "white" data list how to read it? White, can be pure white "1", also is Formica 3, can be white beauty 5, also can be white rich beauty 7, you can use in to read, but the better way is to use the same bit operation in SQL statement.

SELECT * from Table1 where tag & 1 = 1//tag is the column name select * from Table1 where  tag | 1 = Tag

III. recommendations for use of enumerations

When the parameters, return values, variables, and so on can be enumerated, use enumerations as much as possible (consider the stability of the classifications)

The INT type enumeration can be used in most cases, except in the following cases.

Enumerations can be used in a large number of ways, and enumerations less than int are used to conserve space.

Flag enumeration with more than 32 flags.

Here is an example of enumerating the binding MVC3 drop-down list:

Controller code:

namespace mvcstart.controllers{public    class Homecontroller:controller    {public        actionresult getsexlist ()        {            dictionary<string, int> sexlist = new dictionary<string, int> ();            String[] keys = enum.getnames (typeof (Sex));            Array values = enum.getvalues (typeof (Sex));            for (int i = 0; i < keys. Length; i++)            {                sexlist.add (keys[i], (int) values. GetValue (i));            }            Return View (sexlist);        }    }    Public enum sex    {         male = 1,        female = 2, and other        = 3    }}

View Code:

@model dictionary<string, int><select>    @foreach (var item in @Model)    {        <option value= "@ Item. Value "> @item. Key</option>    }</select>

Generated HTML code:

<select>        <option value= "1" >male</option>        <option value= "2" >female</option>        <option value= "3" >other</option></select>

One more example, get enumeration description

public static class GetDescription {//<summary>///        for description/        //</summary>//        < param name= "en" ></param>        ///<returns></returns> public static string description (this 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 ();        }    }    Public enum Sex    {        [Description ("male")] man        = 1,        [Description ("female")]        woman = 2,        [ Description ("others")] Other        = 3    }

C # Enumeration

Related Article

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.