First Question:
A |
does a bitwise or; a bit will be set in the result if it is set in the first value or the second value. (You use it on enums
to create values that are combinations of other values) If you were to use a bitwise and, it wouldn't make very much sense.
It gets used as follows:
[Flags]
enum FileAccess{
None = 0, // 00000000 Nothing is set
Read = 1, // 00000001 The read bit (bit 0) is set
Write = 2, // 00000010 The write bit (bit 1) is set
Execute = 4, // 00000100 The exec bit (bit 2) is set
// ...
ReadWrite = Read | Write // 00000011 Both read and write (bits 0 and 1) are set
// badValue = Read & Write // 00000000 Nothing is set, doesn't make sense
ReadExecute = Read | Execute // 00000101 Both read and exec (bits 0 and 2) are set
}
// Note that the non-combined values are powers of two,
// meaning each sets only a single bit
// ...
// Test to see if access includes Read privileges:
if((access & FileAccess.Read) == FileAccess.Read)
Essentially, you can test if certain bits in an enum
are set; in this case we are testing to see if the bits corresponding to a Read
are set. Values Read
and ReadWrite
would both pass this test (the both have bit zero set); Write
would not (it does not have bit zero set).
// if access is FileAccess.Read
access & FileAccess.Read == FileAccess.Read
// 00000001 & 00000001 => 00000001
// if access is FileAccess.ReadWrite
access & FileAccess.Read == FileAccess.Read
// 00000011 & 00000001 => 00000001
// uf access is FileAccess.Write
access & FileAccess.Read != FileAccess.Read
// 00000010 & 00000001 => 00000000
Second Question:
I think when you say "and/or", you mean "one, the other or both". This is exactly what the ||
(or operator) does. To say "one or the other, but not both", you'd use ^
( the exclusive or opertor).
Truth tables (true==1, false==0):
A B | A || B
------|-------
OR 0 0 | 0
0 1 | 1
1 0 | 1
1 1 | 1 (result is true if any are true)
A B | A ^ B
------|-------
XOR 0 0 | 0
0 1 | 1
1 0 | 1
1 1 | 0 (if both are true, result is false)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…