简体   繁体   中英

Convert integer enum to string

considering the following enum:

public enum LeadStatus 
{ 
    Cold = 1, 
    Warm = 2, 
    Hot = 3, 
    Quote = 5, 
    Convert = 6 
} 

How can I convert the integer value back to string when I pull the value from a database. I've tried:

DomainModel.LeadStatus status = (DomainModel.LeadStatus)Model.Status;

but all I seem to get is "status = 0"

What you are looking for is Enum.Parse.

"Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object."

Here is the MSDN page: http://msdn.microsoft.com/en-us/library/essfb559.aspx

Example:

enum Colour
{
   Red,
   Green,
   Blue
} 

// ...
Colour c = (Colour) Enum.Parse(typeof(Colour), "Red", true);

Courtesy of http://blogs.msdn.com/tims/archive/2004/04/02/106310.aspx

Enum.ParseEnum.ToString之间 ,你应该能够做你需要的一切。

鉴于“Model.Status”是数据库中的整数,它可以恢复为Enum字符串值:

string status  = Enum.GetName(typeof(DomainModel.LeadStatus), Model.Status);

只需在枚举对象上使用ToString()即可

An enumeration in C# is used to provide names for some known values but ANY integer value is permissible in that enumeration, whether it has a named equivalent or not.

In your example, you have not named a zero value, but your status variable initialises to zero. I suspect that it has not changed from this initial value at the point you read it. Therefore, it's string representation is also 0 and you will parse out zero when you parse it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM