C # mutual conversion of Enum, Int, and string

Source: Internet
Author: User

C # mutual conversion of Enum, Int, and string]

1. Enum --> string

(1) Use the object. tostring () method: for example:Colors. Green. tostring() The value is a "green" string; (2) use the static methods of Enum to getname and getnames: public static string getname (type enumtype, object value) public static string [] getnames (type enumtype) Example: enum. getname (typeof (colors), 3) andEnum. getname (typeof (colors), colors. Blue ))All values are "blue"Enum. getnames (typeof (colors ))Returns an enumerated string array.

2. String --> Enum

(1) Use the static method parse of Enum: public static object parse (type enumtype, string value) for example:(Colors) enum. parse (typeof (colors), "Red ")

3. Enum --> int

(1) because the enumeration base type is an integer other than char, it can be forcibly converted. For example:(INT) colors. Red, (Byte) colors. Green

4. 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) using the static method toobject of enum. Public static object toobject (type enumtype, int value) Example: colors color =(Colors) enum. toobject (typeof (colors), 2)The color is colors. Blue.

5. determine whether an integer is defined in the enumeration method: enum. isdefined

Public static bool isdefined (type enumtype, object Value) Example:Enum. isdefined (typeof (colors), n ))

Refer:

1. http://msdn.microsoft.com/zh-cn/library/system.enum (V = vs.110). aspx

2. http://www.cnblogs.com/myx/archive/2011/06/17/Enum-Int-String.html

 

 

 

 

 

 

 

 

 

 

C # mutual conversion of Enum, Int, and string

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.