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

后端 未结 11 1598
陌清茗
陌清茗 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条回答
  •  猫巷女王i
    2020-12-30 06:17

    Question long over, but here's one for reference anyway:

        public static bool HasFlag(this TEnum enumeratedType, TEnum value)
            where TEnum : struct, IComparable, IFormattable, IConvertible
    
        {
            if (!(enumeratedType is Enum))
            {
                throw new InvalidOperationException("Struct is not an Enum.");
            }
    
            if (typeof(TEnum).GetCustomAttributes(
                typeof(FlagsAttribute), false).Length == 0)
            {
                throw new InvalidOperationException("Enum must use [Flags].");
            }
    
            long enumValue = enumeratedType.ToInt64(CultureInfo.InvariantCulture);
            long flagValue = value.ToInt64(CultureInfo.InvariantCulture);
    
            if ((enumValue & flagValue) == flagValue)
            {
                return true;
            }
    
            return false;
        }
    

提交回复
热议问题