微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

字符串值枚举在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中显示一个很好的描述.我不知道它适合你的情况,但把它当作一个选择.

原文地址:https://www.jb51.cc/csharp/94005.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐