字符串值枚举在c#

参见英文答案 > Associating enums with strings in C#26
有没有办法在c#中定义枚举,如下所示?
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;
}

有什么改善?

解决方法

一个替代方案,效率不高但是提供枚举功能是使用一个属性,如下所示:
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中显示一个很好的描述.我不知道它适合你的情况,但把它当作一个选择.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...