Comparing enum flags in C#

后端 未结 7 2273
一个人的身影
一个人的身影 2021-02-07 18:42

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:36

    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;
    }
    

提交回复
热议问题