从枚举属性获取枚举

我有


public enum Als 

{

    [StringValue("Beantwoord")] Beantwoord = 0,

    [StringValue("Niet beantwoord")] NietBeantwoord = 1,

    [StringValue("Geselecteerd")] Geselecteerd = 2,

    [StringValue("Niet geselecteerd")] NietGeselecteerd = 3,

}


public class StringValueAttribute : Attribute

{

    private string _value;


    public StringValueAttribute(string value)

    {

        _value = value;

    }


    public string Value

    {

        get { return _value; }

    }

}

我想将我从组合框选择的项目中的值放入一个int:


int i = (int)(Als)Enum.Parse(typeof(Als), (string)cboAls.SelectedValue); //<- WRONG

这可能吗?如果可以,怎么办?(StringValue与从组合框中选择的值匹配)。


慕标琳琳
浏览 489回答 3
3回答

开心每一天1111

这是我用于此特定目的的几种扩展方法,我将它们重写为使用您的StringValueAttribute,但像Oliver一样,我在代码中使用了DescriptionAttribute。&nbsp; &nbsp; public static T FromEnumStringValue<T>(this string description) where T : struct {&nbsp; &nbsp; &nbsp; &nbsp; Debug.Assert(typeof(T).IsEnum);&nbsp; &nbsp; &nbsp; &nbsp; return (T)typeof(T)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .GetFields()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .First(f => f.GetCustomAttributes(typeof(StringValueAttribute), false)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Cast<StringValueAttribute>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Any(a => a.Value.Equals(description, StringComparison.OrdinalIgnoreCase))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .GetValue(null);&nbsp; &nbsp; }在.NET 4.5中,这可以变得稍微简单一些:&nbsp; &nbsp; public static T FromEnumStringValue<T>(this string description) where T : struct {&nbsp; &nbsp; &nbsp; &nbsp; Debug.Assert(typeof(T).IsEnum);&nbsp; &nbsp; &nbsp; &nbsp; return (T)typeof(T)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .GetFields()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .First(f => f.GetCustomAttributes<StringValueAttribute>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Any(a => a.Value.Equals(description, StringComparison.OrdinalIgnoreCase))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .GetValue(null);&nbsp; &nbsp; }要调用它,只需执行以下操作:Als result = ComboBox.SelectedValue.FromEnumStringValue<Als>();相反,这是一个从枚举值获取字符串的函数:&nbsp; &nbsp; public static string StringValue(this Enum enumItem) {&nbsp; &nbsp; &nbsp; &nbsp; return enumItem&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .GetType()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .GetField(enumItem.ToString())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .GetCustomAttributes<StringValueAttribute>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(a => a.Value)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .FirstOrDefault() ?? enumItem.ToString();&nbsp; &nbsp; }并称之为:string description = Als.NietBeantwoord.StringValue()
打开App,查看更多内容
随时随地看视频慕课网APP