开发者

Help with EnumMemberAttribute?

I have an enum below which I need to be able to reference by passing in "Insured Only". When I do this it says that it cannot be found as the actual enum shows as InsuredOnly. Is there anyway I can pass in the correct value i.e. "Insured Only" instead of InsuredOnly?

 public enum EnumN开发者_Go百科ames  
        {
            Administrator,
            [Description("Insured Only")]
            InsuredOnly, 
        }


Here's a handy generic method that should do what you want:

public T Parse<T>(string description) {
    foreach (FieldInfo field in typeof(T).GetFields()) {
        object[] attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if ((attributes.Length > 0)
            && ((DescriptionAttribute)attributes[0]).Description.Equals(description)
        ) return (T)field.GetRawConstantValue();
    }

    // use default parsing logic if no match is found
    return (T)Enum.Parse(typeof(T), description);
}

Usage example:

EnumNames value = Parse<EnumNames>("Insured Only");


"Insured Only" is a string, where InsuredOnly is an enum. Even if you do a .ToString(), it will be "InsuredOnly"

There are several options here, to name a few:
1) Use a Dictionary<myenum,string> to map the values
2) Use a [Description("my description")] (see this article)
3) Use some kind of token in the enum, say an underscore, and use string.Replace()


You can do this through reflection (did not do any extensive testing on the code, but hopefully you get the idea):

private static T GetEnumValue<T>(string description)
{
    // get all public static fields from the enum type
    FieldInfo[] ms = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static);
    foreach (FieldInfo field in ms)
    {
        // pull out the DescriptionAttribute (if any) from the field
        var descriptionAttribute = field
            .GetCustomAttributes(typeof(DescriptionAttribute), true)
            .FirstOrDefault();
        // Check if there was a DescriptionAttribute, and if the 
        // description matches
        if (descriptionAttribute != null
            && (descriptionAttribute as DescriptionAttribute).Description
                    .Equals(description, StringComparison.OrdinalIgnoreCase))
        {
            // return the field value
            return (T)field.GetValue(null);
        }
    }
    return default(T);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜