如何读取枚举的文本值

时间:2012-07-25 07:14:08

标签: c# wcf

我创建了一个枚举,想要从中读取文本值。 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,
}  

现在我想将enum的值赋给请求对象methodID。我尝试了以下代码,但它没有用:

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

我想要的是将值“01”分配给我将从Enum MethodID获取的请求数据协定(request.ID)的数据成员。我怎么会这个?请帮忙

2 个答案:

答案 0 :(得分:6)

如果你想获得int值,那么你可以将enum声明为

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

答案 1 :(得分:1)

试试这个

    string myEnum = MethodID.Inquiry.ToString();

int value =  (int)MethodID.Inquiry;

有关如何添加自定义属性并在代码中使用它们的更多信息 http://blogs.msdn.com/b/abhinaba/archive/2005/10/20/c-enum-and-overriding-tostring-on-it.aspx