Comparing enum flags in C#

后端 未结 7 1514
囚心锁ツ
囚心锁ツ 2021-02-07 18:37

I need to detect if a flag is set within an enum value, which type is marked with the Flag attribute.

Usually it is made like that:

(value & flag) ==         


        
7条回答
  •  攒了一身酷
    2021-02-07 19:13

    For me it looks overcomplicated. How about this (keeping in mind that enum is always mapped to an integer value type):

    public static bool IsSet(T value, T flags) where T : struct
    {
        // You can add enum type checking to be perfectly sure that T is enum, this have some cost however
        // if (!typeof(T).IsEnum)
        //     throw new ArgumentException();
        long longFlags = Convert.ToInt64(flags);
        return (Convert.ToInt64(value) & longFlags) == longFlags;
    }
    

提交回复
热议问题