Generic extension method to see if an enum contains a flag

前端 未结 8 1394
闹比i
闹比i 2021-02-01 01:56

Considering this:

[Flags]
public enum MyEnum {
    One = 1,
    Two = 2,
    Four = 4,
    Eight = 8
}

public static class FlagsHelper
{
    public static bool          


        
8条回答
  •  忘掉有多难
    2021-02-01 02:26

    I based this method off of a bunch of SO & Google searches, and a by using reflector to see what MS did for the .NET 4 HasFlags method.

    public static class EnumExt
    {
        /// 
        /// Check to see if a flags enumeration has a specific flag set.
        /// 
        /// Flags enumeration to check
        /// Flag to check for
        /// 
        public static bool HasFlag(this Enum variable, Enum value)
        {
            if (variable == null)
                return false;
    
            if (value == null)
                throw new ArgumentNullException("value");
    
            // Not as good as the .NET 4 version of this function, but should be good enough
            if (!Enum.IsDefined(variable.GetType(), value))
            {
                throw new ArgumentException(string.Format(
                    "Enumeration type mismatch.  The flag is of type '{0}', was expecting '{1}'.",
                    value.GetType(), variable.GetType()));
            }
    
            ulong num = Convert.ToUInt64(value);
            return ((Convert.ToUInt64(variable) & num) == num);
    
        }
    
    }
    

    Notes:

    • This handles nulls
    • Does type checking
    • Converts to a ulong, and can handle any positive enum value. Microsoft cautions against the use of negative flags enumerations anyway:

      Use caution if you define a negative number as a flag enumerated constant because many flag positions might be set to 1, which might make your code confusing and encourage coding errors.

提交回复
热议问题