Get Description Attributes From a Flagged Enum

限于喜欢 提交于 2019-12-05 12:37:09

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

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

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>();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!