如何从"名称"的字符串表示中选择枚举值?

use*_*076 7 c# enums

我有这样的枚举

public enum PetType
{
    Dog = 1,
    Cat = 2
}
Run Code Online (Sandbox Code Playgroud)

我也有string pet = "Dog".我怎么回1?我正在考虑的伪代码是:

select Dog_Id from PetType where PetName = pet
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 15

使用该Enum.Parse方法从字符串中获取枚举值,然后转换为int:

string pet = "Dog";
PetType petType = (PetType)Enum.Parse(typeof(PetType), pet);
int petValue = (int)petType;
Run Code Online (Sandbox Code Playgroud)


Mar*_*rek 5

其他人已经建议使用 Enum.Parse() 但要小心此方法,因为它不仅解析枚举的名称,而且还尝试匹配其值。为了清楚起见,让我们看一个小例子:

PetType petTypeA = (PetType)Enum.Parse(typeof(PetType), "Dog");
PetType petTypeB = (PetType)Enum.Parse(typeof(PetType), "1");
Run Code Online (Sandbox Code Playgroud)

两个解析调用的结果都是 PetType.Dog (当然可以转换为 int )。

在大多数情况下,这种行为是可以的,但并非总是如此,并且值得记住 Enum.Parse() 方法的行为方式。