2013-05-22 78 views
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#中的枚舉中的描述中獲取值?

+0

可能的複製 - HTTP: //rogeroverflow.com/q/1033260/2065121 –

+0

@RogerRowland,OP不需要描述,所以我不認爲它是重複的 – Habib

+0

@Habib - 你確定嗎?再次閱讀可能的複本 - 幾乎完全相同。 –

回答

4

您不必添加描述標籤,只要是路過的枚舉值的字符串,因爲ab,存在於枚舉,您可以使用Enum.Parse解析字符串枚舉Test,然後你能得到這樣的相應值:

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

或者你可以使用Enum.TryParse這不會在無效的輸入字符串的情況下拋出異常。像:

Test temp; 
int integerValue; 
if (Enum.TryParse("a", out temp)) 
{ 
    integerValue2 = (int)temp; 
} 
3

對於框架> = 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 
} 
1

通用幫手,讓你的能力得到任何類型枚舉的整型值

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; 
    }