枚举对字符串的描述

时间:2014-02-19 14:28:37

标签: c# enums

我有以下ENUM:

[Flags]
public enum DataFiat {

  [Description("Público")]
  Public = 1,

  [Description("Filiado")]
  Listed = 2,

  [Description("Cliente")]
  Client = 4

} // DataFiat

我创建了一个扩展来获取Enum属性:

public static T GetAttribute<T>(this Enum value) where T : Attribute {

  T attribute;
  MemberInfo info = value.GetType().GetMember(value.ToString()).FirstOrDefault();
  if (info != null) {
    attribute = (T)info.GetCustomAttributes(typeof(T), false).FirstOrDefault();
    return attribute;
  }
  return null;
}

这适用于非Flags枚举......但是当我有:

var x = DataFiat.Public | DataFiat.Listed;
var y = x.GetAttribute<Description>();

y的值为null ...

我想得到“Público,Filiado,Cliente”......就像ToString()一样。

如何更改扩展程序才能使其正常工作?

谢谢

5 个答案:

答案 0 :(得分:2)

您可以使用this

var values = x.ToString()
             .Split(new[] { ", " }, StringSplitOptions.None)
             .Select(v => (DataFiat)Enum.Parse(typeof(DataFiat), v));

获取个别值。然后获取它们的属性值。

这样的事情:

var y2 = values.GetAttributes<DescriptionAttribute, DataFiat>();

public static T[] GetAttributes<T, T2>(this IEnumerable<T2> values) where T : Attribute
{
    List<T> ts =new List<T>();

    foreach (T2 value in values)
    {
        T attribute;
        MemberInfo info = value.GetType().GetMember(value.ToString()).FirstOrDefault();
        if (info != null)
        {
            attribute = (T)info.GetCustomAttributes(typeof(T), false).FirstOrDefault();
            ts.Add(attribute);
        }
    }

    return ts.ToArray();
}

答案 1 :(得分:0)

我想你想做出类似的东西

using System;

public enum ArrivalStatus { Unknown=-3, Late=-1, OnTime=0, Early=1 };

public class Example
{
   public static void Main()
   {
      int[] values = { -3, -1, 0, 1, 5, Int32.MaxValue };
      foreach (var value in values)
      {
         ArrivalStatus status;
         if (Enum.IsDefined(typeof(ArrivalStatus), value))
            status = (ArrivalStatus) value;
         else
            status = ArrivalStatus.Unknown;
         Console.WriteLine("Converted {0:N0} to {1}", value, status);
      }
   }
}
// The example displays the following output:
//       Converted -3 to Unknown
//       Converted -1 to Late
//       Converted 0 to OnTime
//       Converted 1 to Early
//       Converted 5 to Unknown
//       Converted 2,147,483,647 to Unknown

答案 2 :(得分:0)

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;

public static class Program
{
[Flags]
public enum DataFiat
{

  [Description("Público")]
  Public = 1,

  [Description("Filiado")]
  Listed = 2,

  [Description("Cliente")]
  Client = 4

} 

public static ICollection<string> GetAttribute<T>(this Enum value)
{
  var result = new Collection<string>();
  var type = typeof(DataFiat);

  foreach (var value1 in Enum.GetValues(type))
  {
    var memInfo = type.GetMember(value1.ToString());
    var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
    var description = ((DescriptionAttribute)attributes[0]).Description;
    result.Add(description);
  }

  return result;
}

static void Main(string[] args)
{
  var x = DataFiat.Public | DataFiat.Listed;
  var y = x.GetAttribute<DataFiat>();

  var output = string.Join(" ", y.ToArray());
  Console.WriteLine(output);
}
}

我已将T更改为ICollection,但您可以根据需要更改它,或者您可以在方法中记录数据并返回字符串。

答案 3 :(得分:0)

.NET CORE中,您无需执行任何其他库即可

...
ORDER BY CASE WHEN a.Type in (0, 1) THEN a.CreateDate END

并获得标题:

 public enum Divisions
 {
    [Display(Name = "My Title 1")]
    None,
    [Display(Name = "My Title 2")]
    First,
 }

答案 4 :(得分:-1)

我想出了一个基于我之前代码的不同解决方案。它可以使用如下:

  DataFiat fiat = DataFiat.Public | DataFiat.Listed;
  var b = fiat.ToString();
  var c = fiat.GetAttributes<TextAttribute>();

  var d = fiat.GetAttributes<TextAttribute, String>(x => String.Join(",", x.Select(y => y.Value)));

我认为用它来获取属性或用它们做某事很容易。

你怎么看?

如果代码可以某种方式改进,请告诉我。这是代码:

public static List<T> GetAttributes<T>(this Enum value) where T : Attribute {

  List<T> attributes = new List<T>();

  IEnumerable<Enum> flags = Enum.GetValues(value.GetType()).Cast<Enum>().Where(value.HasFlag);

  if (flags != null) {

    foreach (Enum flag in flags) {
      MemberInfo info = flag.GetType().GetMember(flag.ToString()).FirstOrDefault();
      if (info != null)
        attributes.Add((T)info.GetCustomAttributes(typeof(T), false).FirstOrDefault());         
    }

    return attributes;

  }

  return null;

} // GetAttributes   

public static Expected GetAttributes<T, Expected>(this Enum value, Func<List<T>, Expected> expression) where T : Attribute {

  List<T> attributes = value.GetAttributes<T>();

  if (attributes == null)
    return default(Expected);

  return expression(attributes);

} // GetAttributes