带注释的Enum.Parse

时间:2016-08-30 20:00:21

标签: c# json enums

我正在为Windows应用商店应用开发应用,我有这样的代码。

public enum Categories
{
   Cat1,
   Cat2,
   Cat3
}

是否有将string[] cats = {"categoty 1", "category 2", "category 3"}转换为Enum的选项?

我已尝试使用EnumMember属性:

[DataContract]
public enum Categories
{
   [EnumMember(Value = "category 1")]
   Cat1,

   [EnumMember(Value = "category 2")]
   Cat2,

   [EnumMember(Value = "category 3")]
   Cat3
}

...但var cat = Enum.Parse(typeof(Categories), cats[0]);仍然没有运气:

Exception thrown: 'System.ArgumentException' in mscorlib.ni.dll
Requested value 'category 1' was not found.

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

private static T GetValueFromEnumMember<T>(string value)
{
    var type = typeof(T);
    if (type.GetTypeInfo().IsEnum)
    {
        foreach (var name in Enum.GetNames(type))
        {
            var attr = type.GetRuntimeField(name).GetCustomAttribute<EnumMemberAttribute>(true);
            if (attr != null && attr.Value == value)
                return (T)Enum.Parse(type, name);
        }

        return default(T);
    }

    throw new InvalidOperationException("Not Enum");
 }

用法:

var cat = GetValueFromEnumMember<Categories>(cats[0]);