从字符串获取枚举索引

时间:2012-11-06 18:53:04

标签: c# asp.net

当我有一个要与枚举进行比较的字符串时,如何从枚举中获取索引整数(在本例中为0)?

枚举:

public enum Animals
{
    Dog = 0,
    Cat = 1
}

string myAnimal = "Dog";

显然,以下行不起作用,但它可以帮助您理解我想要实现的目标:

int animalNumber = (int)Animals.[myAnimal];

2 个答案:

答案 0 :(得分:11)

喜欢这个吗?

int animalNumber = (int)Enum.Parse(typeof(Animals), "Dog");

答案 1 :(得分:3)

Types t;
if(Enum.TryParse(yourString, out t)) // yourString is "Dog", for example
{
    // use t           // In your case (int)t
}
else
{
    // yourString does not contain a valid Types value
}

OR

try
{
    Types t = (Types)Enum.Parse(typeof(Types), yourString);
    // use t           // In your case (int)t
}
catch(ArgumentException)
{
    // yourString does not contain a valid Types value
}