Comparing enum flags in C#

后端 未结 7 2486
一个人的身影
一个人的身影 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:34

    Personally, I think that look fine because you've wrapped it into a single purpose function. If you had that code scattered through an entire program I think you would have some problems, but what you've created improves clarity everywhere it is used and the function itself is clear enough what it does.

    Just my opinion of course.

    You could though, use the is keyword, which might help a little

    public static bool IsSet(this T value, T flags) where T : Enum
    { 
        if (value is int)
        {
            return ((int)(object)a & (int)(object)b) == (int)(object)b);
        }
        //etc...
    

提交回复
热议问题