Get Description Attributes From a Flagged Enum

前端 未结 3 1032
挽巷
挽巷 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: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 GetDescriptionsAsText(this Enum yourEnum)
    {       
        List descriptions = new List();
    
        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

提交回复
热议问题