2012-07-25 36 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