Use of the C # enumeration

Source: Internet
Author: User
Tags modifiers numeric value
Original Address: http://www.cnblogs.com/kissdodog/archive/2013/01/16/2863515.html First, before you learn the enumeration, listen to the advantages of the enumeration.

1, the enumeration can make the code more clear, it allows the use of descriptive names to represent the integer value.

2. Enumerations make code easier to maintain, helping to ensure that a variable is given a valid, expected value.

3. Enumerations make code easier to enter. Ii. Description of the enumeration

  1. The simple enumeration enumeration is declared using the enum keyword, and is the same as the class. The enumeration itself can have modifiers, but the members of the enumeration are always public and cannot have access modifiers. The 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 enumerated types are static and default to the Int32 type. Each enumeration 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 the int type. Enumeration members cannot be the same, but the values of enumerations can be the same. Enumerating the last member's comma and the semicolon following the curly braces can omit

C # provides classes to facilitate the operation of enumerations, and the following are the common methods of this class:

Method Name
CompareTo Compares this instance to a specified object and returns an indication of the relative value of the two
Equals Indicates whether this instance is equal to the specified object
Format Converts the specified value of the specified enumeration type to its equivalent string representation, based on the specified format
GetName Retrieves the name of a constant with the specified value in the specified enumeration
GetNames Retrieves an array of constant names in the specified enumeration
GetTypeCode Returns the underlying typecode for this instance
Getunderlyingtype Returns the underlying type of the specified enumeration
GetValues An array of constant values in the specified 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 enumerated constants to an equivalent enumeration object. A parameter specifies whether the operation is case insensitive
TryParse Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumeration object. Return value to indicate whether the conversion succeeded

To display the underlying data type for the specified enumeration, simply 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 an enumeration, which is incremented by default starting from 0. But the following example is 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//Member's value can be set to a  Kind, but the member is not good
    }
Console.WriteLine ((int) week.monday); Get value

Example, getting an enumeration name from an enumeration value and getting an enumeration value by an enumeration name

 class program {static void Main (string[) args) {Conso Le.  WriteLine (Enum.getname (typeof (Man), 1));
            Or Liu Bei (by the value obtained the name) string[] array1 = Enum.getnames (typeof (man));   Console.WriteLine (Array1[1]);
            Guan Yu Array array2 = enum.getvalues (typeof (man)); Console.WriteLine (Array2.  GetValue (1));
            Or the Guan Yu Type t = enum.getunderlyingtype (typeof (man));       Console.WriteLine (t);
            Output Int32//By value fetch content int i = 1; String Name = Enum.parse (typeof (Man), i.ToString ()).     ToString ();

            At this time name= "Liu Bei" Console.WriteLine (Name);
            Get content from 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. Symbol Enumeration

Flag enumeration to be declared at the top with the [System.flags] attribute. and enumerations support combinatorial operations. Let's take a look at an example

    Class program
    {
        static void Main (string[] args)
        {
            var mans = Week. White | Week. Beauty;  The assignment is either    001 or 100, and the result is
            Console.WriteLine ((int) man);
            if (Man & Week. White) = = Week. White)       //101 
            man {                                    //001 white-bit phase,
                Console.WriteLine ("This person white");      001 If the result is white, you can reverse the launch of
            Man containing white}
            else
            {
                Console.WriteLine ("This person black");
            }
            Console.readkey ();
        }

    [System.flags]
    Public enum Week
    { 
        white = 1,  //001
        rich = 2,  //010
        mei = 4,  //100
    }

This bitwise operation is very useful and also supports bit operations 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 request. Like what:

A "white beauty" stored as a database of the value of the database, then the deposit is the integral type 5.

Then I want to read out all the "white" data list how to read it. White, can be pure white "1", is also Bai Fu 3, can be white beauty 5, also can be white rich beauty 7, you can use in to read, but the better way is in the SQL statement also use bit operations.

1 1//tag is the name

of the column SELECT * from Table1 where  1 = Tag

III. Recommendations for the use of enumerations

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

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

Enumerations can be used in a large number of times, in order to conserve space by using enumerations less than int.

Flag enumeration with more than 32 flags.

Here's 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, 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" 
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.