Get Description Attributes From a Flagged Enum

前端 未结 3 1034
挽巷
挽巷 2020-12-19 11:46

I am trying to create an extension method that will return a List containing all the Description attributes for only the set values o

3条回答
  •  不思量自难忘°
    2020-12-19 12:03

    This is a compact solution using LINQ which also checks for null in case not all of the values have attributes:

    public static List GetFlagEnumAttributes(this Enum flagEnum) where T : Attribute
    {
       var type = flagEnum.GetType();
       return Enum.GetValues(type)
          .Cast()
          .Where(flagEnum.HasFlag)
          .Select(e => type.GetMember(e.ToString()).First())
          .Select(info => info.GetCustomAttribute())
          .Where(attribute => attribute != null)
          .ToList();
    }
    

提交回复
热议问题