C # mutual conversion of Enum, Int, and String,

Source: Internet
Author: User

C # mutual conversion of Enum, Int, and String,

Enum provides a base class for enumeration. The base type 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 ))

 

Public enum EmployeeType

{

RegularEmployee,

StoreManager,

ChainStoreManager,

DepartmentManager,

Supervisor

}

We can use the ToString () method to obtain the following information.

 

EmployeeType employee = EmployeeType. ChainStoreManager;

Console. WriteLine (employee. ToString ());

Console. WriteLine (EmployeeType. ChainStoreManager. ToString ());

 

/*

Output result:

 

ChainStoreManager

ChainStoreManager

*/

 

But how can we obtain results like "Chain Store Manager" with spaces? We cannot create an enumerative member that contains spaces. Otherwise, your code cannot be compiled. In fact, we have many solutions to solve this problem.

 

1. Create a ing between enumerated members and strings (arrays or hash tables can be used)

2. Specify the result of the enumerated member ToString () as the key to the resource file.

3. Use reflection .... (I will talk about it below)

 

Use attributes in Enumeration

 

I will use attributes to associate a string with enumeration members. The following is a simple example to illustrate how this is done.

 

Public class EnumDescriptionAttribute: Attribute

{

Private string m_strDescription;

Public EnumDescriptionAttribute (string strPrinterName)

{

M_strDescription = strPrinterName;

}

 

Public string Description

{

Get {return m_strDescription ;}

}

}

The EnumDescriptionAttribute class inherits from Attribute, which contains a String-type Attribute Description. Next, it is associated with all the members of the enumeration EmployeeType.

 

Public enum EmployeeType

{

[EnumDescription ("Regular Employee")]

RegularEmploye,

[EnumDescription ("Store Manager")]

StoreManager,

[EnumDescription ("Chain Store Manager")]

ChainStoreManager,

[EnumDescription ("Department Manager")]

DepartmentManager,

[EnumDescription ("On Floor Supervisor")]

Supervisor

}

 

Get attribute values from Enumeration

 

To get the attribute value, I must use reflection. Below is a simple example:

 

// Setup the enum

EmployeeType employee = EmployeeType. ChainStoreManager;

 

// Get the field informaiton

FieldInfo fieldInfo = employee. GetType (). GetField ("ChainStoreManager ");

 

// Get the attributes for the enum field

Object [] attribArray = fieldInfo. GetCustomAttributes (false );

 

// Cast the one and only attribute to EnumDescriptionAttribute

EnumDescriptionAttribute attrib = (EnumDescriptionAttribute) attribArray [0];

 

// Write the description

Console. WriteLine ("Description: {0}", attrib. Description );

 

/*

Input result:

Chain Store Manager

*/

The most important line of code is FieldInfo fieldInfo = employee. getType (). getField ("ChainStoreManager"); note that the enumerated member name ChainStoreManager can be replaced by the ToString () method.

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.