2

我有一个像

public enum Test {a = 1, b, c, d, e }

然后我有一个方法,我将'a'作为参数传递,但我需要从枚举中检索相应的值并Integer从方法返回值

public int Getvalue(string text)        
{                
    int value = //Need to convert text in to int value.    
    return value;   
}

text作为“a”或“b”或“c”传递,但结果需要 1、2 或 3。我尝试了一些在网上找到的解决方案,但似乎都希望我[Description]在枚举中添加标签以获得价值。

是否可以从 C# 枚举中的描述中获取价值?

4

3 回答 3

3

不用加description标签,只要将枚举值作为字符串传递即可,因为a, b, 存在于枚举中,可以使用Enum.Parse将字符串解析为EnumTest即可得到对应的值喜欢:

var value = Enum.Parse(typeof(Test), "a");
int integerValue = (int)value;

或者您可以使用Enum.TryParsewhich 在输入字符串无效的情况下不会引发异常。喜欢:

Test temp;
int integerValue;
if (Enum.TryParse("a", out temp))
{
    integerValue2 = (int)temp;
}
于 2013-05-22T12:05:08.843 回答
3

对于 Framework >= 4.0,您可以使用Enum.TryParse

public int GetValue(string text)
{
    Test t;
    if (Enum.TryParse(text, out t)
        return (int)t;       
    // throw exception or return a default value
}
于 2013-05-22T12:05:43.323 回答
1

使您能够获取任何类型的枚举 int 值的通用助手

    public static int? GetValue<T>(string text)
    {
        var enumType = typeof (T);
        if (!enumType.IsEnum)
            return null;

        int? val;
        try
        {
            val = (int) Enum.Parse(enumType, text);
        }
        catch (Exception)
        {
            val = null;
        }

        return val;
    }
于 2013-05-22T12:12:03.550 回答