3

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

枚举:

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

string myAnimal = "Dog";

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

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

2 回答 2

13

像这样?

int animalNumber = (int)Enum.Parse(typeof(Animals), "Dog");
于 2012-11-06T18:54:51.490 回答
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
}

或者

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
}
于 2012-11-06T19:11:10.657 回答