如何将字符串转换为枚举值为整数?

use*_*064 2 c# enums

可能重复:
如何在C#中将字符串转换为枚举?
枚举返回int值

我已声明一个枚举: -

public enum Car
        {
            SELECT = 0,
            AUDI = 1,
            NISSAN = 2,
            HONDA = 3,
            LINCOLN = 4
        } 
Run Code Online (Sandbox Code Playgroud)

现在我需要enum的int值匹配: -

private int GetCarType(string CarName)
        {
            foreach(var item in Enum.GetNames(typeof(Car))
            {
                if (item.ToLower().Equals(CarName.ToLower()))
                    //return int value of Enum of matched item; ???????
            }
Run Code Online (Sandbox Code Playgroud)

预期结果: -

int i = GetCarType(CarName); //suppose CarName is AUDI, it should return 1;
Console.write(i);

Result :- 1
Run Code Online (Sandbox Code Playgroud)

我如何获得枚举的价值?更好的编码实践.

Chr*_*ain 6

如果要将字符串转换为枚举,则应使用Enum.Parse而不是遍历名称.

然后只需转换为整数:

var iAsInteger = (Int32)i;
Run Code Online (Sandbox Code Playgroud)


Rob*_*vey 3

var result = (int)System.Enum.Parse(typeof(Car), carName)
Run Code Online (Sandbox Code Playgroud)

http://msdn.microsoft.com/en-us/library/essfb559.aspx

这取代了你的GetCarType功能。您不再需要迭代枚举名称。