C#, Flags Enum, Generic function to look for a flag

后端 未结 11 1594
陌清茗
陌清茗 2020-12-30 05:43

I\'d like one general purpose function that could be used with any Flags style enum to see if a flag exists.

This doesn\'t compile, but if anyone has a suggestion, I

11条回答
  •  太阳男子
    2020-12-30 06:18

    Today, you can set the c# language version to >=7.3 and use the next code as the reference:

    public static class EnumExt
    {
        public static IEnumerable Explode(this TEnum enumValue) where TEnum : Enum
        {
            var res = Enum.GetValues(enumValue.GetType())
                .Cast()
                .Where(x => enumValue.HasFlag(x));
            return res;
        }
    
        public static string ExplodeToString(this TEnum enumValue, string delimeter = ",") where TEnum : Enum
        {
            return string.Join(delimeter, Explode(enumValue));
        }
    }
    

提交回复
热议问题