如何从Enum获取字符串值[重复]

时间:2022-05-01 20:54:25

This question already has an answer here:

这个问题在这里已有答案:

I am confused with Enum. This is my enum

我和Enum很困惑。这是我的枚举

enum Status
{
   Success = 1,
   Error = 0
}


public void CreateStatus(int enumId , string userName)
{
     Customer t = new Customer();
     t.Name = userName;
    // t.Status = (Status)status.ToString(); - throws build error
     t.Status = //here I am trying if I pass 1 Status ="Success", if I pass 0 Status = "Error"

}

Error - Cannot convert string to enum.Status

错误 - 无法将字符串转换为enum.Status

public class Customer
{
  public string Name { get; set;}
  public string Status {get; set;}
}

How do I set the Status properties of the customer objecj using the Enum Status.?

如何使用枚举状态设置客户对象的状态属性。

(No If-Else or switch ladder)

(没有If-Else或切换*)

2 个解决方案

#1


4  

You just need to call .ToString

你只需要调用.ToString

 t.Status = Status.Success.ToString();

ToString() on Enum from MSDN

来自MSDN的Enum上的ToString()

If you have enum Id passed, you can run:

如果您传递了枚举ID,则可以运行:

t.Status = ((Status)enumId).ToString();

It casts integer to Enum value and then call ToString()

它将整数转换为Enum值,然后调用ToString()

EDIT (better way): You can even change your method to:

编辑(更好的方式):您甚至可以将您的方法更改为:

public void CreateStatus(Status status , string userName)

and call it:

并称之为:

CreateStatus(1,"whatever");

and cast to string:

并转换为字符串:

t.Status = status.ToString();

#2


1  

Its easy you can use ToString() method to get the string value of an enum.

很容易就可以使用ToString()方法获取枚举的字符串值。

enum Status
{
   Success = 1,
   Error = 0
}

string foo = Status.Success.ToString(); 

Update

更新

Its easier if you include the type of Enum within your method's inputs like below:

如果您在方法的输入中包含Enum类型,则更容易,如下所示:

public void CreateStatus(Status enums, string userName)
{
     Customer t = new Customer();
     t.Name = userName;
     t.Status = enums.Success.ToString();

}

#1


4  

You just need to call .ToString

你只需要调用.ToString

 t.Status = Status.Success.ToString();

ToString() on Enum from MSDN

来自MSDN的Enum上的ToString()

If you have enum Id passed, you can run:

如果您传递了枚举ID,则可以运行:

t.Status = ((Status)enumId).ToString();

It casts integer to Enum value and then call ToString()

它将整数转换为Enum值,然后调用ToString()

EDIT (better way): You can even change your method to:

编辑(更好的方式):您甚至可以将您的方法更改为:

public void CreateStatus(Status status , string userName)

and call it:

并称之为:

CreateStatus(1,"whatever");

and cast to string:

并转换为字符串:

t.Status = status.ToString();

#2


1  

Its easy you can use ToString() method to get the string value of an enum.

很容易就可以使用ToString()方法获取枚举的字符串值。

enum Status
{
   Success = 1,
   Error = 0
}

string foo = Status.Success.ToString(); 

Update

更新

Its easier if you include the type of Enum within your method's inputs like below:

如果您在方法的输入中包含Enum类型,则更容易,如下所示:

public void CreateStatus(Status enums, string userName)
{
     Customer t = new Customer();
     t.Name = userName;
     t.Status = enums.Success.ToString();

}