• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

从枚举属性获取枚举

用户头像
it1352
帮助1

问题说明

我有

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 中:

And I would like to put the value from the item I selected of a combobox into a int:

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

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

Is this possible, and if so, how? (the StringValue matches the value selected from the combobox).

正确答案

#1

这里有一个辅助方法,可以为您指明正确的方向.

Here's a helper method that should point you in the right direction.

protected Als GetEnumByStringValueAttribute(string value)
{
    Type enumType = typeof(Als);
    foreach (Enum val in Enum.GetValues(enumType))
    {
        FieldInfo fi = enumType.GetField(val.ToString());
        StringValueAttribute[] attributes = (StringValueAttribute[])fi.GetCustomAttributes(
            typeof(StringValueAttribute), false);
        StringValueAttribute attr = attributes[0];
        if (attr.Value == value)
        {
            return (Als)val;
        }
    }
    throw new ArgumentException("The value '"   value   "' is not supported.");
}

要调用它,只需执行以下操作:

And to call it, just do the following:

Als result = this.GetEnumByStringValueAttribute<Als>(ComboBox.SelectedValue);

这可能不是最好的解决方案,因为它与 Als 相关联,并且您可能希望使此代码可重用.您可能希望从我的解决方案中删除代码以返回属性值,然后在您的问题中使用 Enum.Parse.

This probably isn't the best solution though as it's tied to Als and you'll probably want to make this code re-usable. What you'll probably want to strip out the code from my solution to return you the attribute value and then just use Enum.Parse as you are doing in your question.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfhggk
系列文章
更多 icon
同类精品
更多 icon
继续加载