在Enums的通用方法中检索属性

时间:2014-06-19 02:03:11

标签: c# generics enums

使用以下枚举:

public enum AuthorizeRole
{
    // The Name is used to Seed the database 
    // The description is used to display a friendly name to the user

    [ScaffoldColumn(false)]
    Undefined,

    [Display(Name = "Administrator", Description = "Administrator")]
    Administrator,

    [Display(Name = "Customer", Description = "Customer")]
    Customer,

    [Display(Name = "Business User", Description = "Business User")]
    BusinessUser
}

我写了下面的类,以便能够检索枚举的所有值:

public static class Enum<T> 
  where T : struct, IComparable, IFormattable, IConvertible
{
    public static IEnumerable<T> GetValues()
    {
        var result = ((T[])Enum.GetValues(typeof(T)))
            .ToList();

        return result;
    }
}

用于检索属性元数据的Extension方法:

public static class EnumExtensions
{
    public static string GetName(this Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DisplayAttribute[] attributes = fi.GetCustomAttributes(typeof(DisplayAttribute), false) as DisplayAttribute[];

        if (attributes != null && attributes.Length > 0)
        {
            return attributes[0].Name;
        }
        else
        {
            return value.ToString();
        }
    }
}

所以现在做的很简单:

foreach (var role in Enun<AuthorizeRole>.GetValues())
{
  string roleName = role.GetName();
}

我不知道如何创建方法GetNames()(这可能不可能?):

public static class Enum<T> 
  where T : struct, IComparable, IFormattable, IConvertible
{
    public static IEnumerable<T> GetValues()
    {
        // ...
    }

    public static IEnumerable<T> GetNames()
    {
        var result = ((T[])Enum.GetValues(typeof(T)))
            // at this point since T is not typeof(System.Enum) it fails
            .Select(t => t.GetName()) 
            .ToList();

        return result;
    }
}

DotNetFiddle Example

1 个答案:

答案 0 :(得分:1)

由于我使用.ToString()来反映价值,我得到了它。

public static class Enum<T>
  where T : struct, IComparable, IFormattable, IConvertible
{
    public static IEnumerable<string> GetNames()
    {
        var result = ((T[])Enum.GetValues(typeof(T)))
            .Select(t => new
            {
                failName = t.ToString(),
                displayAttribute = (typeof(T)
                    .GetField(t.ToString())
                    .GetCustomAttributes(typeof(DisplayAttribute), false) 
                      as DisplayAttribute[]).FirstOrDefault()
            })
            .Select(a => a.displayAttribute != null 
              ? a.displayAttribute.Name: a.failName)
            .ToList();

        return result;
    }

DotNetFiddle - Example