当我有一个要与枚举进行比较的字符串时,如何从枚举中获取索引整数(在本例中为 0)?
枚举:
public enum Animals
{
Dog = 0,
Cat = 1
}
string myAnimal = "Dog";
显然,以下行不起作用,但它可能会帮助您理解我想要实现的目标:
int animalNumber = (int)Animals.[myAnimal];
像这样?
int animalNumber = (int)Enum.Parse(typeof(Animals), "Dog");
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
}