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
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;
q ^ QueryFlag.ByProduct
q & (~QueryFlag.ByProduct)
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
{
return (flags & (~flag)) != flags;
}
, T . , , operator ~ can't be applied to type T. ?