Get Description Attributes From a Flagged Enum

前端 未结 3 1033
挽巷
挽巷 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<T> GetFlagEnumAttributes<T>(this Enum flagEnum) where T : Attribute
    {
       var type = flagEnum.GetType();
       return Enum.GetValues(type)
          .Cast<Enum>()
          .Where(flagEnum.HasFlag)
          .Select(e => type.GetMember(e.ToString()).First())
          .Select(info => info.GetCustomAttribute<T>())
          .Where(attribute => attribute != null)
          .ToList();
    }
    
    0 讨论(0)
  • 2020-12-19 12:22

    HasFlag is your friend. :-)

    The extension method below uses the GetDescription extension method you've posted above, so ensure you have that. The following should then work:

    public static List<string> GetDescriptionsAsText(this Enum yourEnum)
    {       
        List<string> descriptions = new List<string>();
    
        foreach (Enum enumValue in Enum.GetValues(yourEnum.GetType()))
        {
            if (yourEnum.HasFlag(enumValue))
            {
                descriptions.Add(enumValue.GetDescription());
            }
        }
    
        return descriptions;
    }
    

    Note: HasFlag allows you to compare a given Enum value against the flags defined. In your example, if you have

    Result y = Result.Value1 | Result.Value2 | Result.Value4;
    

    then

    y.HasFlag(Result.Value1)
    

    should be true, while

    y.HasFlag(Result.Value3)
    

    will be false.

    See also: https://msdn.microsoft.com/en-us/library/system.enum.hasflag(v=vs.110).aspx

    0 讨论(0)
  • 2020-12-19 12:22

    You can iterate all values from enum and then filter them that isn't contained into your input value.

        public static List<T> GetAttributesByFlags<T>(this Enum arg) where T: Attribute
        {
            var type = arg.GetType();
            var result = new List<T>();
            foreach (var item in Enum.GetValues(type))
            {
                var value = (Enum)item;
                if (arg.HasFlag(value)) // it means that '(arg & value) == value'
                {
                    var memInfo = type.GetMember(value.ToString())[0];
                    result.Add((T)memInfo.GetCustomAttribute(typeof(T), false));
                }
            }
            return result;
        }
    

    And you get list of attributes that you want:

    var arg = Result.Value1 | Result.Value4;
    List<DescriptionAttribute> attributes = arg.GetAttributesByFlags<DescriptionAttribute>();
    
    0 讨论(0)
提交回复
热议问题