Conversion of C # enum,int,string to each other

Source: Internet
Author: User

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

An enum provides a base class for an enumeration whose underlying type can be any integral type except Char. If you do not explicitly declare an underlying type, use Int32. Programming languages typically provide syntax to declare enumerations that consist of a set of named constants and their values.

Note: The base type of an enumeration type is any integral type except Char, so the value of the enumeration type is an integer value.

The Enum provides some useful static methods:

(1) Methods to compare instances of an enumeration class

(2) method of converting the value of an instance to its string representation

(3) method to convert the string representation of a number to an instance of this class

(4) A method that creates an instance of the specified enumeration and value.

Example: Enum Colors {Red, Green, Blue, Yellow};

Enum-->string

(1) using the Object.ToString () method: The value of Colors.Green.ToString () is a "Green" string;

(2) using the static method of enum GetName and GetNames:

public static string GetName (Type enumtype,object value)

public static string[] GetNames (Type enumtype)

For example: Enum.getname (typeof (Colors), 3)) and Enum.getname (typeof (Colors), colors.blue) are all "Blue" values

Enum.getnames (typeof (Colors)) returns an array of enumeration strings.

String-->enum

(1) The static method of using Enum, parse:

public static Object Parse (Type enumtype,string value)

For example: (Colors) Enum.parse (typeof (Colors), "Red")

Enum-->int

(1) Because the base type of the enumeration is an integral type other than Char, it is possible to cast.

For example: (int) colors.red, (byte) colors.green

Int-->enum

(1) You can cast an integral type to an enumeration type.

For example: Colors color = (Colors) 2, then color is Colors.blue

(2) using the static method of enum Toobject.

public static Object Toobject (Type enumtype,int value)

For example: Colors color = (Colors) enum.toobject (typeof (Colors), 2), then color is Colors.blue

method to determine whether an integral type is defined in an 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 easily get to the following information by using the ToString () method

Employeetype employee = Employeetype.chainstoremanager;
Console.WriteLine (employee. ToString ());
Console.WriteLine (EmployeeType.ChainStoreManager.ToString ());

/*
Output Result:

Chainstoremanager
Chainstoremanager
*/

But how can we get the results similar to "Chain Store Manager" including spaces? We cannot create an enumeration member that contains spaces, otherwise your code will not compile, and in fact we have a lot of solutions to solve this problem.

1. Create a map between the enumeration member and the string (you can use an array or a hash table)
2. Specify the result of the enumeration member ToString () as the key to the resource file
3. Use reflection .... (I'll talk about it below)

Using attributes in enumerations

I will use attributes to achieve the purpose of associating a string to an enumeration member, and below is a simple example of 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 property description of type string, which is associated to all 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
}


Gets the value of the property from the enumeration

In order to get the value of the property, I have to use it to reflect the following 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
*/ 

One of the most important line of code: FieldInfo FieldInfo = employee. GetType (). GetField ("Chainstoremanager"); We note that hard-coded enumeration member names inside the Chainstoremanager can actually be replaced by the ToString () method.

Conversion of C # enum,int,string to each other

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.