搜索包含斜杠的枚举描述

时间:2014-11-24 15:29:22

标签: c# enums

为了尝试简短,我创建了以下枚举

public enum Frequency
{
    [Description("Monthly")]
    Monthly,
    [Description("Quarterly")]
    Quarterly,
    [Description("N/A")]
    NA
}

然后我有一个使用相同描述字符串的组合框。

当我选择一个新的选择,特别是“N / A”选择时,它无法正确读取。

我用来根据传入的字符串搜索正确的枚举的代码是......

/// Returns an enum of the specified type that matches the string value passed in. Note this does ignore case
<param name="value">The string value.</param>        
public static TEnum GetEnum<TEnum>(string value)
{
    if (string.IsNullOrEmpty(value))
    {
        // Default not set value name
        value = "None";
    }
     return (TEnum)System.Enum.Parse(typeof(TEnum), value.Replace(" ", string.Empty), true);
}

所以当值=“N / A”时,我得到以下错误..

"An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll"

其他信息:未找到请求值'N / A'。“

我似乎无法理解为什么会发生这种情况。还有另一个预先存在的组合框,其中的解密还包含一个'/'字符,并发生相同的错误。所以它看起来不是我做错了,而只是枚举字符串检查的行为。

任何了解这导致问题的原因都会令人难以置信。 :) 谢谢!

修改: 更多信息..

所以这是触发枚举搜索的代码..

if (this.FrequencyCombo.SelectedItem != null && !this.FrequencyCombo.SelectedItem.Equals(Utilities.GetDescription(currentLoan.Frequency)))
        {
            currentLoan.Frequency = Utilities.GetEnum<Frequency>(this.FrequencyCombo.SelectedItem.ToString());
        }

3 个答案:

答案 0 :(得分:2)

使用以下内容替换您的方法,您尝试将描述与值匹配:

    /// <summary>
    /// Gets the Enum from a matching description value
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="description"></param>
    /// <returns></returns>
    public static T GetValueFromDescription<T>(string description)
    {
        var type = typeof(T);
        if (!type.IsEnum) throw new InvalidOperationException();
        foreach (var field in type.GetFields())
        {
            var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attribute != null)
            {
                if (attribute.Description == description)
                { 
                    return (T)field.GetValue(null);
                }
            }
            else
            {
                if (field.Name == description)
                { 
                    return (T)field.GetValue(null);
                }
            }
        }

        throw new ArgumentException("Enum description not found.", "Description");            
    }

答案 1 :(得分:0)

Enum.Parse接受一个表示枚举值名称的字符串参数,而不是描述,即Enum.ToString()返回的内容。您需要一个按描述查找枚举值的方法,如下所示:

public static TEnum GetEnumByDescription<TEnum>(string desc) where TEnum : struct
{
    if(string.IsNullOrEmpty(desc))
    {
        return default(TEnum);
    }
    foreach(var field in typeof(TEnum).GetFields(BindingFlags.Static | BindingFlags.Public))
    {
        var attr = (DescriptionAttribute)field.GetCustomAttribute(typeof(DescriptionAttribute));
        if(attr != null && attr.Description == desc)
        {
            return (TEnum)field.GetValue(null);
        }
    }
    return default(TEnum);
}

答案 2 :(得分:0)

这样的事情会做。它列出了所有成员,获取了他们的描述,并将它们与您正在寻找的字符串进行比较。

    public static T GetByDescription<T>(string description) {
        return Enum.GetValues(typeof(T))
            .OfType<T>()
            .First(f => {
                var memberInfo = typeof(T).GetMember(f.ToString());
                var desc = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                return desc.Length == 1 && ((DescriptionAttribute)desc[0]).Description.Equals(description, StringComparison.InvariantCultureIgnoreCase);
            });
    }

如何使用它:

GetByDescription<Frequency>("Monthly");
GetByDescription<Frequency>("N/A");

相关:Getting attributes of Enum's value