将枚举转换为列表的 EnumsNET 通用方法

EnumsNET generic method to cast enum to list

错误:类型 'Type Name' 必须是不可为 null 的值类型才能将其用作泛型类型或方法 'Generic Identifier'

中的参数 'Parameter Name'
 public static List<GenericEnum> GetEnumSelection<T>()
    {
        return Enum.GetValues(typeof(T)).Cast<T>().Select(v =>
        {
            var item = new GenericEnum { Id = Convert.ToInt32(v), Text = **v.AsString<T>**(EnumFormat.Description) };
            return item;
        }).ToList();
    }

我正在尝试编写将枚举 [Description] 属性映射到 class GenericEnum 的通用 class。问题在于 Enums.Net .AsString<> 方法,因为它无法转换为 T.

有什么建议吗?

您需要将函数中的 T 约束为 struct, Enum:

 public static List<GenericEnum> GetEnumSelection<T>() where T : struct, Enum

顺便说一下,如果您使用的是 Enum.NET,您可能应该使用他们的 Enums.GetValues<T>,因为性能会更好。