c# - C#中的字符串值枚举

标签 c# .net enums

<分区>

有什么方法可以像下面这样在 C# 中定义枚举?

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

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

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 中显示漂亮的描述。我不确定它是否适合您的情况,但可以将其扔掉。

关于c# - C#中的字符串值枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2979848/

相关文章:

c# - Moq 具有匿名类型的函数

objective-c - 使用typedef枚举时,返回类型枚举EnumName返回枚举成员时会产生编译器错误

c# - 如何将整个字符串与正则表达式匹配?

c# - 使用本地项目引用覆盖 nuget 包引用

c# - .NET WinForm ComboBox - 如何改变 DropDown 行为

c# - HttpContext.Current.User.Identity.Name 在 .ashx 处理程序中不起作用

json - 为没有字段的 Java 枚举创建读/写

java - 使用常量字符串作为 Enum 构造函数参数

c# - 混淆c#/silverlight源代码的方法

.net - 为什么 F# inline 会导致 11 倍的性能提升