在泛型方法中检索枚举的属性

本文关键字:属性 枚举 检索 泛型方法 | 更新日期: 2023-09-27 18:09:30

使用以下Enum:

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
}

我编写了下面的类来检索Enum的所有值:

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;
    }
}

和一个检索属性元数据的扩展方法:

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示例

在泛型方法中检索枚举的属性

因为我使用.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 -示例