问题描述
我有
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).
推荐答案
下面是应该指向你在正确的方向上的辅助方法。
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);
这可能不是,虽然,因为它是依赖于阿尔斯
,你可能会想使这个code可重复使用的最佳解决方案。那么就用什么,你可能会想带出code从我的解决方案来回报你的属性值和 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.
这篇关于获得从枚举属性枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!