Skip to main content
 首页 » 编程设计

C#之通过属性获取所有枚举值

2024年02月05日10qq78292959

我有以下枚举:

public enum KodEnum 
{ 
    [EnumType(EnumType = "Task")] 
    TaskTab, 
    [EnumType(EnumType = "Task")] 
    TaskReason, 
    [EnumType(EnumType = "Action")] 
    ActionTab, 
    [EnumType(EnumType = "Action")] 
    ActionReason 
} 
 
public class EnumTypeAttribute : Attribute 
{ 
    public string EnumType { get; set; } 
} 

我想获取所有枚举类型为“任务”的枚举的列表。

我该怎么做?

请您参考如下方法:

这样的事情应该会让你上路......

var enumValues = (from member in typeof(KodEnum).GetFields() 
                  let att = member.GetCustomAttributes(false) 
                                  .OfType<EnumTypeAttribute>() 
                                  .FirstOrDefault() 
                  where att != null && att.EnumType == "Task" 
                  select member.GetValue(null)) 
                 .Cast<KodEnum>() 
                 .ToList(); 

如果你想要 int 值,那么就转换它:

var enumValues = (from member in typeof(KodEnum).GetFields() 
                  let att = member.GetCustomAttributes(false) 
                                  .OfType<EnumTypeAttribute>() 
                                  .FirstOrDefault() 
                  where att != null && att.EnumType == "Task" 
                  select (int)member.GetValue(null)) 
                 .ToList(); 

和全 lambda 解决方案:

        var enumValues = typeof(KodEnum) 
            .GetFields() 
            .Select(x => new  
                {  
                    att = x.GetCustomAttributes(false) 
                             .OfType<EnumTypeAttribute>() 
                             .FirstOrDefault(),  
                    member = x  
                }) 
            .Where(x => x.att != null && x.att.EnumType == "Task") 
            .Select(x => (int)x.member.GetValue(null)) 
            .ToList();