Gur*_*epS 1 .net c# enums bit-manipulation
我正在阅读有关标志枚举和按位运算符的信息,并且遇到了以下代码:
enum file{
read = 1,
write = 2,
readandwrite = read | write
}
Run Code Online (Sandbox Code Playgroud)
我在某处读到了为什么有一个包容性或声明以及如何不能有&,但找不到文章.有人可以刷新我的记忆并解释推理吗?
另外,我怎么说和/或?例如.如果dropdown1 ="你好"和/或dropdown2 ="你好"....
谢谢
Dan*_*ant 14
第一个问题:
A |是按位还是; 如果在第一个值或第二个值中设置了一个位,将在结果中设置一个位.(您使用它enums来创建其他值的组合的值)如果您使用按位,并且它将没有多大意义.
它使用如下:
[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)
Run Code Online (Sandbox Code Playgroud)
基本上,您可以测试是否设置了某些位enum; 在这种情况下,我们正在测试是否设置了对应于a的位Read.值Read和ReadWrite都将通过此测试(两者都设置为零); Write不会(它没有设置零位).
// 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
Run Code Online (Sandbox Code Playgroud)
第二个问题:
我想当你说"和/或"时,你的意思是"一个,另一个或两个".这正是||(或运营商)所做的.要说"一个或另一个,但不是两个",你要使用^(独家或opertor).
真值表(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)
Run Code Online (Sandbox Code Playgroud)