c#中的字符串值枚举

时间:2010-06-05 09:46:41

标签: c# .net enums

有没有办法在c#中定义enum,如下所示?

public enum MyEnum : string
{
    EnGb = "en-gb",
    FaIr = "fa-ir",
    ...
}

好的,根据erick方法和链接,我使用它来检查提供的描述中的有效值:

public static bool IsValidDescription(string description)
{
    var enumType = typeof(Culture);
    foreach (Enum val in Enum.GetValues(enumType))
    {
        FieldInfo fi = enumType.GetField(val.ToString());
        AmbientValueAttribute[] attributes = (AmbientValueAttribute[])fi.GetCustomAttributes(typeof(AmbientValueAttribute), false);
        AmbientValueAttribute attr = attributes[0];
        if (attr.Value.ToString() == description)
            return true;
    }
    return false;
}

有什么改进吗?

5 个答案:

答案 0 :(得分:13)

另一个替代方案,不是高效但给出枚举功能是使用属性,如下所示:

public enum MyEnum
{
  [Description("en-gb")]
  EnGb,
  [Description("fa-ir")]
  FaIr,
  ...
}

类似于扩展方法,这就是我使用的方法:

public static string GetDescription<T>(this T enumerationValue) where T : struct
{
  var type = enumerationValue.GetType();
  if (!type.IsEnum) throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
  var str = enumerationValue.ToString();
  var memberInfo = type.GetMember(str);
  if (memberInfo != null && memberInfo.Length > 0)
  {
    var attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
    if (attrs != null && attrs.Length > 0)
      return ((DescriptionAttribute) attrs[0]).Description;
  }
  return str;
}

然后你可以这样称呼它:

MyEnum.EnGb.GetDescription()

如果它有一个描述属性,那么你可以得到它,如果没有,你会获得.ToString()版本,例如"EnGb"。我有这样的事情的原因是直接在Linq-to-SQL对象上使用枚举类型,但能够在UI中显示漂亮的描述。我不确定它适合你的情况,但可以把它作为一种选择扔掉。

答案 1 :(得分:7)

关于马修的答案,我建议你使用Dictionary<MyEnum, String>。我将它用作静态属性:

class MyClass
{
    private static readonly IDictionary<MyEnum, String> dic = new Dictionary<MyEnum, String>
    {
        { MyEnum.EnGb, "en-gb" },
        { MyEnum.RuRu, "ru-ru" },
        ...
    };

    public static IDictionary<MyEnum, String> Dic { get { return dic; } }
}

答案 2 :(得分:3)

如果您的所有名称/值都与此完全相同,则可以正常创建枚举。

public enum MyEnum
{
   EnGb
   FaIr
}

然后当您需要实际值时,将枚举名称作为字符串,将其设为小写并在中间添加-

string value = MyEnum.EnGb.ToString().ToLower().Insert(2, "-");

答案 3 :(得分:1)

没有。您只需使用Dictionary<String, String>即可。枚举的类型必须是除char之外的整数类型。这样可以有效地比较它们。

答案 4 :(得分:1)

只能通过在枚举值上使用属性来间接实现,如下所示:

public enum MyEnum {
  [DefaultValue("en-gb")]
  EnGb,
  [DefaultValue("fa-ir")]
  FaIr,
  ...
}

然后,您可以通过读取枚举的静态字段上的自定义属性,使用反射检索字符串值。