Get Description Attributes From a Flagged Enum

前端 未结 3 1037
挽巷
挽巷 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

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

        public static List GetAttributesByFlags(this Enum arg) where T: Attribute
        {
            var type = arg.GetType();
            var result = new List();
            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 attributes = arg.GetAttributesByFlags();
    

提交回复
热议问题