2012-07-25 40 views
1

我創建了一個Enum並希望從中讀取文本值。枚舉如下:如何閱讀枚舉的文本值

public enum MethodID 
{ 
    /// <summary> 
    /// The type of request being done. Inquiry. 
    /// </summary> 
    [EnumTextValue("01")] 
    Inquiry, 

    /// <summary> 
    /// The type of request being done. Update 
    /// </summary> 
    [EnumTextValue("02")] 
    Update, 
} 

現在我想分配一個請求對象methodID的枚舉值。我想下面的代碼,但它沒有工作:

request.ID = Enum.GetName(typeof(MethodID), MethodID.Inquiry); 

我想應該是將值「01」分配給請求數據合同的數據成員(request.ID),我將從枚舉放在methodID取。我將如何得到這個?請幫助

回答

5

使用它們。如果你只想得到int值,那麼你可以聲明枚舉作爲

public enum MethodID 
{ 
    [EnumTextValue("01")] 
    Inquiry = 1, 

    [EnumTextValue("02")] 
    Update = 2, 
} 

,然後用鑄造爲int:

ind id = (int)MethodID.Inquiry; 

如果您想從屬性得到字符串值,那麼這是靜態輔助方法

///<summary> 
/// Allows the discovery of an enumeration text value based on the <c>EnumTextValueAttribute</c> 
///</summary> 
/// <param name="e">The enum to get the reader friendly text value for.</param> 
/// <returns><see cref="System.String"/> </returns> 
public static string GetEnumTextValue(Enum e) 
{ 
    string ret = ""; 
    Type t = e.GetType(); 
    MemberInfo[] members = t.GetMember(e.ToString()); 
    if (members.Length == 1) 
    { 
     object[] attrs = members[0].GetCustomAttributes(typeof (EnumTextValueAttribute), false); 
     if (attrs.Length == 1) 
     { 
      ret = ((EnumTextValueAttribute)attrs[0]).Text; 
     } 
    } 
    return ret; 
} 
+0

我想在我的請求成員ID中獲得值「01」(正如在Enum中定義的那樣)。我也可以通過硬編碼的方式來實現,如request.ID =「01。但我想在Enum中存儲這個值,並且我想從中檢索它。 – 2012-07-25 07:51:30

+0

謝謝。有效。 – 2012-07-25 08:00:26