[C# Basic Detailed Explanation] (8) Enumeration Type

8.1 Introduction to enumeration

An enumeration is a type of value that contains a set of named constants. An enumeration is a data type called an enumeration type, which is also used to store data.

8.2 The usefulness of enumeration

1) For example, in the case, if you need to reuse specific strings from Monday to Sunday, you can define an enumeration called week. If it is not defined as an enumeration, there may be many ways to write it, such as Monday, Monday, Monday, etc., all three of which represent the same day.

2) For example, in the fruit cutting game, there are many types of fruits, such as bananas, apples, oranges, watermelons, etc. At this time, an enumeration type called fruit can be defined to store the fruit types.

3) For example, in a game, there are usually many occupations, such as fighters, mages, shooters... and many other types of occupations, so you can define an enumerated type called occupation. Or there are many types of firearms, such as submachine guns, rifles, pistols, sniper rifles, etc., you can define an enumeration type called firearms.

8.3 Enumeration Syntax

[public] enum name

{

value 1,

value 2,

value 3,

……

}

public: Access modifier, public and public, can be accessed anywhere.

enum: keyword, the keyword to declare the enumeration.

Enumeration name: It must comply with the Pascal naming convention.

Notice:

Declaring the enumeration under the namespace and outside the class means that all classes under this namespace can use this enumeration.

An enumeration is a variable type, but the enumeration declaration, assignment, and use are different from those of ordinary variable types.

You can declare a variable of enumeration type, such as variable c1, use the name of the enumeration type as a prefix, and set a named constant to assign a value in the enumeration.

By default, the type of enum is int, the first member of the enumeration will be 0, and the value of each successive enumeration member will increase by 1.

default enumeration value
enum WeekDays
{
    Monday,     // 0
    Tuesday,    // 1
    Wednesday,  // 2
    Thursday,   // 3
    Friday,     // 4
    Saturday,   // 5
    Sunday      // 6
}
Assign values ​​to enum members

Enumeration members can be assigned different values. Changes to the default value of an enumeration member will automatically assign incremental values ​​to other members in sequence.

You can even assign different values ​​to each member.

enum WeekDays
{
    Monday,            // 0
    Tuesday,           // 1
    Wednesday = 3,  // 3
    Thursday,       // 4
    Friday,         // 5
}
byte enumeration

Enums can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long or ulong. However, enums cannot be of type string.

Specify the inheritance type after enum as: type. The bytes enum is defined below.

enum Fruits: byte
{
    Apple = 1,
    Banana = 5,
    Pear = 6,
    Watermelon = 10, 
    Strawberry = 11, 
    Pineapple = 15
}

8.4 Enumeration conversion instance

base instance
class Program
{
    public enum Color 
    {
        Red,  //若修改为Red=1,则序号依次累加,默认为0
        Green,
        Blue  //注意最后一个常量值逗号可以省略
    }
    static void Main(string[] args)
    {
        Color c1  = Color.Red;
        Console.WriteLine(c1);
    }
}	

Output result:

Red

Enumeration type is forced to int type

Each symbol in the enumeration list represents an integer value, an integer value greater than the symbol before it, by default, the value of the first enumeration symbol is 0. When converting the enumeration type to int type, the subscript of the enumeration element starts from 0 by default. The specific usage is as follows:

public enum Color 
{
    Red,  //默认为0,若修改为Red=1,则序号依次累加
    Green,
    Blue  //注意最后一个常量值逗号可以省略
}
class Program
{
    static void Main(string[] args)
    {
        int x = (int)Color.Red;
        int y = (int)Color.Blue;
        Console.WriteLine("Red={0}\nBlue={1}",x,y);
    }
}	

Output result:

Red=0

Blue=2

The int type is forcibly converted to the enumeration type

If the int type can be successfully converted to the enumeration type according to the element subscript, it will be converted to the value of the corresponding enumeration element, and if the conversion fails, the corresponding int value will be output.

//声明一个枚举类型Week
public enum Week
{
    星期一 = 10,
    星期二,
    星期三
}
class Program
{
    static void Main(string[] args)
    {
        Week week = (Week)3;
        Console.WriteLine(week);
        Console.WriteLine((Week)10);
        Console.WriteLine((Week)100);
        Console.ReadKey();
    }
}

Output result:

3

Monday

100

Enumeration type and string type

8.5 Enums and strings

All types can be converted to string types, including enumeration types, by calling ToString().

Enumeration type conversion string type

grammar:

Week week=Week. Monday;

week.ToString();

Enumeration types can be converted to and from int and string types. The enumeration type is compatible with the int type by default, so it can be converted to each other through the syntax of mandatory type conversion. When converting a value that is not in an enumeration, no exception will be thrown, but the number will be displayed directly.

string type conversion enumeration type

grammar:

Enumeration type identifier to be converted = (enumeration type to be converted) Enum.Parse(typeof(enumeration type to be converted), "string to be converted");

If the converted string is a number, no exception will be thrown even if it is not in the enumeration.

If the converted string is text, an exception will be thrown if there is none in the enum.

8.6 Enumeration Case Exercise

The user selects an online status, and after acceptance, the user's input is converted into an enumeration type and printed to the console again.
public enum QQState
{
    OnLine=1,
    OffLine,
    Leave,
    Busy,
    QMe
}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("请选择您的qq在线状态 1--OnLine 2--offLine 3--Leave 4--Busy 5--QMe");
        string input = Console.ReadLine();
        switch (input)
        {
            case "1":
                QQState s1 = (QQState)Enum.Parse(typeof(QQState), 	input);
                Console.WriteLine("您选择的在线状态是{0}", s1);
                break;
            case "2":
                QQState s2 = (QQState)Enum.Parse(typeof(QQState), 	input);
                Console.WriteLine("您选择的在线状态是{0}", s2);
                break;
            case "3":
                QQState s3 = (QQState)Enum.Parse(typeof(QQState), 	input);
                Console.WriteLine("您选择的在线状态是{0}", s3);
                break;
            case "4":
                QQState s4 = (QQState)Enum.Parse(typeof(QQState), input);
                Console.WriteLine("您选择的在线状态是{0}", s4);
                break;
            case "5":
                QQState s5 = (QQState)Enum.Parse(typeof(QQState), 	input);
                Console.WriteLine("您选择的在线状态是{0}", s5);
                break;
        }
        Console.ReadKey();
    }
}

Guess you like

Origin blog.csdn.net/Y1RV1NG/article/details/129671043
Recommended