2011-11-16 80 views
5

我有这样如何从“名称”的字符串表示中选择一个枚举值?

public enum PetType 
{ 
    Dog = 1, 
    Cat = 2 
} 

枚举我也有string pet = "Dog"。我如何返回1?伪代码,我想的是:

select Dog_Id from PetType where PetName = pet 
+0

可能重复我如何创建一个字符串表示枚举? c#](http://stackoverflow.com/questions/1130377/how-do-i-create-an-enum-from-a-string-representation-c-sharp) – nawfal

回答

13

使用Enum.Parse方法从字符串的枚举值,然后转换为INT:

string pet = "Dog"; 
PetType petType = (PetType)Enum.Parse(typeof(PetType), pet); 
int petValue = (int)petType; 
0
(PetType)Enum.Parse(typeof(PetType), pet) 
3

如果您使用的是.NET 4您可以使用Enum.TryParse

PetType result; 
if (Enum.TryParse<PetType>(pet, out result)) 
    return (int)result; 
else 
    throw something with an error message 
3

其他已经建议使用Enum.Parse(),但要小心使用这种方法,是因为它不仅解析枚举的名称,而且还试图匹配它的值。 要清楚,让我们检查小例子:

PetType petTypeA = (PetType)Enum.Parse(typeof(PetType), "Dog"); 
PetType petTypeB = (PetType)Enum.Parse(typeof(PetType), "1"); 

共同作用的结果解析调用将PetType.Dog(可浇铸当然INT)。

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

0

你可以使用一个字符串作为参数一样的[

int pet=1; 
PetType petType = (PetType)Enum.Parse(typeof(PetType), pet.ToString()); 

或者

string pet="Dog"; 
PetType petType = (PetType)Enum.Parse(typeof(PetType), pet); 
+0

如果你已经有了这个号码,你可以将其转换为枚举值:'petType =(PetType)1' –

+0

是的,这是正确的,它是其他方式显示结果,这个答案在其他评论 –