C # Enum, Int, and String mutual conversion enumeration conversion,
Enum provides the base class for enumeration.Basic TypeIt can be any integer except Char. If the basic type is not explicitly declared, Int32 is used. Programming Languages generally provide syntax to declare an enumeration consisting of a group of named constants and their values.
Note: The base type of the enumeration type is any integer except Char, so the enumerated value is an integer value.
Enum provides some practical static methods:
(1) method for comparing enumeration instances
(2) method of converting the Instance value to its String Representation
(3) how to convert the string representation of a number to an instance of this class
(4) Create an instance with the specified enumeration value.
Example: enum Colors {Red, Green, Blue, Yellow };
Enum --> String
(1) Use the Object. ToString () method: for example, the value of Colors. Green. ToString () is a "Green" string;
(2) Use the static method GetName and GetNames of Enum:
Public static string GetName (Type enumType, Object value)
Public static string [] GetNames (Type enumType)
For example, the values of Enum. GetName (typeof (Colors), 3) and Enum. GetName (typeof (Colors), Colors. Blue) are "Blue"
Enum. GetNames (typeof (Colors) returns an enumerated string array.
String --> Enum
(1) Use the static method Parse of Enum:
Public static Object Parse (Type enumType, string value)
Example: (Colors) Enum. Parse (typeof (Colors), "Red ")
Enum --> Int
(1) because the enumeration base type is an integer other than Char, it can be forcibly converted.
Example: (int) Colors. Red, (byte) Colors. Green
Int --> Enum
(1) An integer can be forcibly converted to an enumeration type.
For example: Colors color = (Colors) 2, then color is Colors. Blue
(2) Use the static method ToObject of Enum.
Public static Object ToObject (Type enumType, int value)
For example: Colors color = (Colors) Enum. ToObject (typeof (Colors), 2), then color is Colors. Blue
Method for determining whether an integer is defined in enumeration: Enum. IsDefined
Public static bool IsDefined (Type enumType, Object value)
Example: Enum. IsDefined (typeof (Colors), n ))