可能有枚举字符串?

Joa*_*nge 7 .net c# enums

我希望有一个枚举,如:

enum FilterType
{
   Rigid = "Rigid",
   SoftGlow = "Soft / Glow",
   Ghost = "Ghost",
}
Run Code Online (Sandbox Code Playgroud)

怎么做到这一点?有一个更好的方法吗?它将被用于一个对象的实例,它将被序列化/反序列化.它也会填充下拉列表.

Sha*_*owe 11

using System.ComponentModel;   
enum FilterType
{
    [Description("Rigid")]
    Rigid,
    [Description("Soft / Glow")]
    SoftGlow,
    [Description("Ghost")]
    Ghost ,
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样得到价值

public static String GetEnumerationDescription(Enum e)
{
  Type type = e.GetType();
  FieldInfo fieldInfo = type.GetField(e.ToString());
  DescriptionAttribute[] da = (DescriptionAttribute[])(fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false));
  if (da.Length > 0)
  {
    return da[0].Description;
  }
  return e.ToString();
}
Run Code Online (Sandbox Code Playgroud)

  • 好方法.你甚至可以将它作为所有枚举的扩展方法. (4认同)

Dav*_*kle 9

不,但是如果你想要限制"const"字符串并像enum一样使用它们,这就是我所做的:

public static class FilterType
{
   public const string Rigid = "Rigid";
   public const string SoftGlow =  "Soft / Glow";
   public const string Ghost ="Ghost";
}
Run Code Online (Sandbox Code Playgroud)