如何将字符串设置为枚举变量?

时间:2012-01-23 14:14:58

标签: c# .net string enums

  

可能重复:
  Cast string to enum with enum attribute

我有enum这样:

public enum IddFilterCompareToCurrent
{
    [StringValue("Ignore")]
    Ignore,
    [StringValue("Pre-Post")]
    PrePost,
    [StringValue("Custom")]
    Custom
}

我还有一些DomainUpDown控件,它们填充了我定义的枚举的相同值,因为枚举不接受-字符,我必须使用Attributes来匹配它们的内容为DomainUpDown

现在我的问题是我如何将所选的domainupdown项插入到该枚举类型的变量中?

类似的东西:

private IddFilterCompareToCurrent myEnum = Enum.Parse(typeof(IddFilterCompareToCurrent), domainUpDown1.SelectedItem.ToString());

我收到此错误:

  

无法隐式转换类型'对象' to' Filtering.IddFilterCompareToCurrent'。存在显式转换(您是否错过了演员?)

4 个答案:

答案 0 :(得分:3)

这样做:

private IddFilterCompareToCurrent myEnum = 
(IddFilterCompareToCurrent )Enum.Parse(typeof(IddFilterCompareToCurrent ),domainUpDown1.SelectedItem.ToString());

Enum.Parse会返回Object,因此您需要投射它。

答案 1 :(得分:1)

您需要为将读取StringValueAttribute

的枚举创建包装器对象
public class EnumWrapper<TEnum>
{
    public static EnumWrapper<TEnum>[] GetItems()
    {
        Type type = typeof(TEnum);
        var enumObjects = Enum.GetValues(type);
        var enumTyped = enumObjects.Select((v) => (TEnum)v);
        EnumWrapper<TEnum>[] ret = enumTyped.Select((e) => new EnumWrapper<TEnum>(e));

        return ret;
    }
}

public string DisplayName { get; private set; }
public TEnum  EnumValue { get; private set; }

private EnumWrapper(TEnum enumVal)
{
   Type type = enumVal.GetType();
   // Read attributes here. I'm leaving this out. if you need it, let me know.
   DisplayName = GetStringValueAttributeOfEnumValue(enumVal);
   EnumValue = enumVal;
}

答案 2 :(得分:1)

您需要解析使用等于输入值的属性进行注释的枚举的字段名称的值:

FieldInfo[] fields = typeof(IddFilterCompareToCurrent).GetFields();
                foreach (FieldInfo fi in fields) 
                {
                    object[] atts = fi.GetCustomAttributes(typeof(StringValueAttribute), false);
                    if (atts != null && atts.Length > 0) 
                    {
                        StringValueAttributeatt = atts[0] as StringValueAttribute;
                        if (att.Value == domainUpDown1.SelectedItem.ToString()) return (IddFilterCompareToCurrent)Enum.Parse(typeof(IddFilterCompareToCurrent), fi.Name);
                    }
                }

答案 3 :(得分:0)

你可以改变枚举并做这样的事情......如果你这样做,它将返回枚举的名称。否则ActLaly类的[StringValue(“..”)是什么样的.. ?

    enum IddFilterCompareToCurrent 
    { 

        Ignore,     
        PrePost,
        Custom 
    } 

usage: 
    var strEnumNames = Enum.GetNames(typeof(IddFilterCompareToCurrent));

返回一个字符串[]“忽略”,“PrePost”,“自定义”;

 if you have this already working please ignore..