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

后端 未结 11 1593
陌清茗
陌清茗 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:00

    No, you can't do this with C# generics. However, you could do:

    public static bool IsEnumFlagPresent(T value, T lookingForFlag) 
        where T : struct
    {
        int intValue = (int) (object) value;
        int intLookingForFlag = (int) (object) lookingForFlag;
        return ((intValue & intLookingForFlag) == intLookingForFlag);
    }
    

    This will only work for enums which have an underlying type of int, and it's somewhat inefficient because it boxes the value... but it should work.

    You may want to add an execution type check that T is actually an enum type (e.g. typeof(T).BaseType == typeof(Enum))

    Here's a complete program demonstrating it working:

    using System;
    
    [Flags]
    enum Foo
    {
        A = 1,
        B = 2,
        C = 4,
        D = 8
    }
    
    class Test
    {
        public static Boolean IsEnumFlagPresent(T value, T lookingForFlag) 
            where T : struct
        {
            int intValue = (int) (object) value;
            int intLookingForFlag = (int) (object) lookingForFlag;
            return ((intValue & intLookingForFlag) == intLookingForFlag);
        }
    
        static void Main()
        {
            Console.WriteLine(IsEnumFlagPresent(Foo.B | Foo.C, Foo.A));
            Console.WriteLine(IsEnumFlagPresent(Foo.B | Foo.C, Foo.B));
            Console.WriteLine(IsEnumFlagPresent(Foo.B | Foo.C, Foo.C));
            Console.WriteLine(IsEnumFlagPresent(Foo.B | Foo.C, Foo.D));
        }
    }
    

提交回复
热议问题