C # Illustrated tutorial 11th Zhang Yi

Source: Internet
Author: User

Enumeration enumeration sets the underlying type and explicit value
Implicit member number bit flag flags attribute
Example of using bit flags supplemental enumeration enumeration for enumerations

An enumeration is a programmer-defined type that is the same as a class or struct.

    • Like structs, enumerations are value types, so they store their data directly, rather than storing them separately as references and data
    • Enumerate members with only one type: named Integer value constants

Example: enumeration Example

Keyword Enumeration name  ↓      ↓enum  trafficlight{    Green,    ←  comma-delimited, no semicolon    Yellow,    Red }

Each enum type has an underlying integer type, which defaults to int.

    • Each enumeration member is given a constant value of the underlying type
    • By default, the compiler assigns the first member a value of 0 and assigns the value to each subsequent member 1 more than the previous one
var t1=Trafficlight.green; var t2=Trafficlight.yellow; var t3=trafficlight.red; Console.WriteLine ("{0},\t{1}", T1, (int) t1); Console.WriteLine ("{0},\t{1}", T2, (int) t2); Console.WriteLine ("{0},\t{1}", T3, (int) t3);

Setting the underlying type and explicit values

You can put the colon and the type name after the enumeration name so that you can use an integer type other than int. The type can be any integer type. All member constants belong to the underlying type of the enumeration.

enum TrafficLight:ulong{    ...}

The value of a member constant can be any value of the underlying type. Enumeration members cannot have duplicate names, but can have duplicate values.

enum trafficlight{    Green  =ten,    =,    Red    =  the }
Implicit member number

If a member constant is not initialized, the compiler implicitly assigns a value to it.
Cases:

enumcardsuit{Hearts,//0 Because this is the first itemClubs,//1 1 larger than beforeDiamonds,//2 larger than before 1, and so on belowspades, maxsuits}enumfacecards{//Member//The assigned valueJack = One,//11 Explicit set-upQueen,//12 1 larger than beforeKing,//13 1 larger than beforeAce//14 1 larger than beforenumberoffacecards=4,//4 Explicit set-upSomeothervalue,//5 1 larger than beforeHighestfacecard=ace//more than 14 defines the ace}

Bit flag

Programmers have long used different bits of single word as a compact way to set on/off flags. This section is called the glyph (flag word). Enumeration provides an easy way to implement it.

The general steps are as follows.

    1. Determine how many bit flags are required and choose an unsigned type that has enough bits to hold it
    2. Make sure that each bit position represents the declaration and give them a name. Declares a checked integer type enumeration, with each member represented by a bit position
    3. Use the bitwise OR (or) operator to set the appropriate bit in the word that holds the bit flag
    4. Use the bitwise-and (and) operator, or the Hasflag method to unlock the bit flags

Example: The following enumeration represents an option for a deck of cards in a card game.

    • A member has a name that represents a binary option
      • Each option is represented by a special bit in the word, and the bit position remains a 0 or a 1
      • Because a bit flag indicates a bit that is either on or off, you do not want to use 0 as a member value. It already has a meaning: all the bit marks are off
    • In 16 notation, each 16-mechanism number is represented by 4 bits. Because of the connection between the bit pattern and the 16 binary notation, the 16 binary rather than the 10 binary is used when processing bit patterns.
    • Using the Flags attribute decoration (decorate) enumeration is actually unnecessary, but there are some additional conveniences that will be discussed shortly. The attribute behaves as a string enclosed in brackets, appearing before the language construct. In this case, the attribute appears before the enumeration declaration. Characteristics in the 24th chapter elaborated
[Flags] enum Carddecksettings:uint{    singledeck    =0x01// bit 0    Largepictures =0x02// bit 1    fancynumbers  =0x04// bit 2    Animation     =0x08  // bit 3}

To create a word with the appropriate bit flags, you need to declare a variable of that enumeration type and use the bitwise OR operator to set the desired bit.

Carddecksettings ops= carddecksettings.singledeck                     |  Carddecksettings.fancynumbers                     | Carddecksettings.animation;

You can use the Hasflag Boolean method in the enumeration type to determine whether the glyph contains a specific set of bit flags. Call the Hasflag method on the glyph and the bit flags that will be checked as parameters. If the specified bit flag is set, Hasflag returns True, otherwise false is returned.

bool usefancynumbers=ops. Hasflag (carddecksettings.fancynumbers);

Hasflag can also detect multiple bit flags.

    • The first line creates a test word instance, called TestFlags, and sets the animation and Fancynumbers flag bits
    • Then pass the call TestFlags as a parameter to the Hasflag method.
    • Hasflag detects whether all the flags in the test word have been set in the OPS flag word. Returns False if True is returned
Carddecksettings testflags=carddecksettings.animation| carddecksettings.fancynumbers; bool useanimationandfancynumbers=ops. Hasflag (TestFlags);

Another way to determine whether one or more of the specified methods are set is to use the bitwise AND operator.

bool usefancynumbers=    (Ops&carddecksettings.fancynumbers) = = Carddecksettings.fancynumbers;

Flags feature
[Flags] enum Carddecksettings:uint{    singledeck    =0x01// bit 0    Largepictures =0x02// bit 1    fancynumbers  =0x04// bit 2    Animation     =0x08  // bit 3}

The flags feature does not change the result of the calculation, but it provides some handy features. First, it informs the compiler, the Object Browser, and other tools that look at this code, that the members of the enumeration can be used not only as individual values, but also in combination by a bitwise flag. This allows the browser to interpret the variables of the enumerated type more appropriately.
Second, it allows enumeration of the values of the ToString method bit flags to provide more formatting information, and the ToString method compares the enumeration's constant members with an enumeration value bit parameter. If the member matches, ToString returns the string name of the member.
Example: An enumeration without flags

enumCarddecksettings:UINT{Singledeck=0x01,//bit 0Largepictures =0x02,//bit 1Fancynumbers =0x04,//bit 2Animation =0x08  //bit 3}classprogram{Static voidMain () {carddecksettings ops; OPS=carddecksettings.fancynumbers; Console.WriteLine (OPS.        ToString ()); OPS=carddecksettings.fancynumbers|carddecksettings.animation; Console.WriteLine (OPS.    ToString ()); }}

The second line of the output above 12=8+4. Because fancynumbers sets the bit to the value 4,animation sets the bit to the value 8.
However, if you precede the enumeration declaration with the flags attribute, you will be told that the ToString method bit can be considered separately. Run the code that contains the flags attribute, as the result:


Examples of using bit flags
[Flags]enumCarddecksettings:UINT{Singledeck=0x01,//bit 0Largepictures =0x02,//bit 1Fancynumbers =0x04,//bit 2Animation =0x08  //bit 3}classmyclass{BOOLUsesingledeck =false, Usebigpics=false, Usefancynumbers=false, Useanimation=false, Useanimationandfancynumbers=false;  Public voidsetoptions (carddecksettings Ops) {Usesingledeck=OPS.        Hasflag (Carddecksettings.singledeck); Usebigpics=OPS.        Hasflag (Carddecksettings.largepictures); Usefancynumbers=OPS.        Hasflag (carddecksettings.fancynumbers); Useanimation=OPS.        Hasflag (carddecksettings.animation); Carddecksettings TestFlags=carddecksettings.animation|carddecksettings.fancynumbers; Useanimationandfancynumbers=OPS.    Hasflag (TestFlags); }     Public voidPrintOptions () {Console.WriteLine ("Option Settings:"); Console.WriteLine ("Use single Deck-{0}", Usesingledeck); Console.WriteLine ("Use Large Pictures-{0}", Usebigpics); Console.WriteLine ("Use Fancy Numbers-{0}", usefancynumbers); Console.WriteLine ("Show Animation-{0}", useanimation); Console.WriteLine ("Show Animation and Fancynumbers-{0}", useanimationandfancynumbers); }}classprogram{Static voidMain () {varMc=NewMyClass (); Carddecksettings Ops=Carddecksettings.singledeck|carddecksettings.fancynumbers|carddecksettings.animation; Mc.        SetOption (OPS); Mc.    PrintOptions (); }}

Add-on to enumerations

Enumeration has only a single member type: Declared member constants

    • You cannot use modifiers on members. They both implicitly have and enumerate the same accessibility
    • Because the member is a constant, it can be accessed even when the enumeration variable is not available. Use枚举类型名.成员名

Example: Direct access to enumeration constants

Console.WriteLine ("{0}", Trafficlight.green);

Enumerations are a unique type. Comparing members of different enumeration types can cause compile-time errors.
Example: enumeration comparison

    • The first if is correct, because it compares different members of the same enumeration type
    • The second if produces an error because it compares members from different enumeration types, although they have the same structure and member names
enumfirstenum{Mem1, Mem2}enumsecondenum{Mem1, Mem2}classprogram{Static voidMain () {if(firstenum.mem1<firstenum.mem2) Console.WriteLine ("True"); if(FIRSTENUM.MEM1&LT;SECONDENUM.MEM1)//errors, different enumeration typesConsole.WriteLine ("True"); }}

The. NET enum type also includes some useful static methods:

    • The GetName method returns the name of the enumeration member of the response, with an enumeration type object and an integer argument
    • The GetNames method returns the names of all the members in the enumeration type object as arguments

Example: GetName, GetNames sample

enum trafficlight{    Green,    Yellow,    Red}class  program{    static  void  Main ()    {        Console.WriteLine ("Second member of TrafficLight is {0}\n  ", Enum.getname (typeof(TrafficLight),1));         foreach (var in Enum.getnames (typeof(TrafficLight)))        {            Console.WriteLine (name);     }}}

C # Illustrated tutorial 11th Zhang Yi

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.