Comparing enum flags in C#

后端 未结 7 1632
囚心锁ツ
囚心锁ツ 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:18

    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...
    

提交回复
热议问题