How to find out what items are listed in an enumeration?

In this question , I use the xor operator between enumwith an attribute [Flags]as follows:

[Flags]
enum QueryFlag
{
  None = 0x1,
  ByCustomer = 0x2,
  ByProduct = 0x4,
  ByDate = 0x8
}
QueryFlag flags = QueryFlag.ByCustomer | QueryFlag.ByProduct;

To add a QueryFlag, of course, we must use a statement |.

flags |= QueryFlag.ByDate;

To delete one, I will answer Dan Tao differently . I use:

flags ^= QueryFlag.ByProduct;

while he uses:

flags &= ~QueryFlag.ByProduct;

Obviously, his answer is correct and understandable. I thought I made a mistake. But after deep thought, I got:

a,b         a^b         a&(~b)
0,0          0           0
0,1          1           0   //the difference
1,0          1           1
1,1          0           0

And now I knew my mistake. ^incorrect when you try to delete one item that does not exist.

QueryFlag q = QueryFlag.ByCustomer | QueryFlag.ByDate;
//try to remove QueryFlag.ByProduct which doesn't exist in q
q ^ QueryFlag.ByProduct    //equals to add ByProduct to q, wrong!
q & (~QueryFlag.ByProduct) // q isn't changed, remain the original value. correct!

But I have another question: how can I find out if it contains qone element? Based on Dan Tao's answer, I wrote an extension:

public static bool Contains(this QueryFlag flags, QueryFlag flag)
{
   return (flags & (~flag)) != flags;
}

, , , ! , :

(QueryFlag.ByProduct | QueryFlag.ByDate).Contains(QueryFlag.None)   //false
(QueryFlag.ByProduct | QueryFlag.ByDate).Contains(QueryFlag.ByDate)  //true

:

(QueryFlag.ByProduct | QueryFlag.ByDate).Contains(QueryFlag.ByDate | QueryFlag.ByCustomer) //true, but I suppose it false

, , ? . : .Contains enum [Flags].

public static bool Contains<T>(this T flags, T flag) where T : Enum//with [Flags]
{
    return (flags & (~flag)) != flags;
}

, T . , , operator ~ can't be applied to type T. ?

+3
2

:

public static bool Contains(this QueryFlag flags, QueryFlag flag)
{
   return (flags & (~flag)) != flags;
}

true, flags - ( ) , flag, , .

:

public static bool Contains(this QueryFlag flags, QueryFlag flag)
{
   return (flags & flag) == flag;
}

Enum.HasFlag(), . :

QueryFlag qf = ...;
if (qf.HasFlag(QueryFlag.ByCustomer))
    // ...
0

:

return (flags & mask) == mask;

true, , mask, flags.

return (flags & mask) != 0;

true - , mask, flags.

, struct. T .

public static bool Contains<T>(this T flags, T mask) where T : struct
{
    return (flags & mask) == mask;
}
0

Source: https://habr.com/ru/post/1765557/


All Articles