SoFunction
Updated on 2025-03-06

In-depth analysis of the definition and use of enum types in c#

introduce
An enum is a specified constant whose base type can be any integer except Char.
If the underlying type is not explicitly declared, Int32 is used.
Programming languages ​​usually provide syntax to declare an enum composed of a set of named constants and their values.

definition
The default cardinality starts from O, and you can also specify a value.
enum Days { Saturday=1, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };

use
Colors myColors = ;
string strColor=();
int    IntColor=(int)myColors ;

bit or
Colors myColors = | | ;

bit and
Colors myColors = & & ;

Traversal

Copy the codeThe code is as follows:

foreach (string s in (typeof(Days)))
(s + "--" + (typeof(Days), s).ToString());

Convert
Copy the codeThe code is as follows:

Colors mc=Colors (typeof(Colors ), "red");
if ((typeof(Days), "Monday"))
Days ds= (Days)(typeof(Days), "Monday");

Example 2:
Copy the codeThe code is as follows:

    public enum NoticeType
    {
        Notice = 'A',
        LabRule = 'H',
        HotInformation = 'N',
        Column = 'C',
        All = '1',
        Null = '0'
     }
//Create a new enumeration type
        NoticeType noticeType1 = ;

//Convert the enum type to string d="Column"
        string d = ();

//Get the cardinality of the enumeration type dd='C'
        char dd = (char)noticeType1;

//Get the corresponding enum type through the cardinality noticeType2 =
//(NoticeType)'A';  Both methods are OK
        NoticeType noticeType2 = (NoticeType)("A");

//Get the enum type by name noticeType3 =
        NoticeType noticeType3 = (NoticeType)(typeof(NoticeType), "Notice");