c# - 按位或 | 是什么意思运营商呢?

标签 c# .net enums bit-manipulation

我在阅读有关标志枚举和按位运算符的内容时,遇到了这段代码:

enum file{
read = 1,
write = 2,
readandwrite = read | write
}

我在某处读到关于为什么有包含性或声明以及为什么不能有 &,但找不到文章。有人可以帮我重温一下并解释一下原因吗?

此外,我怎么说和/或?例如。如果 dropdown1="hello"和/或 dropdown2="hello"...

谢谢

最佳答案

第一个问题:

A | 做按位或;如果在第一个值或第二个值中设置了某个位,则会在结果中设置它。 (您在 enums 上使用它来创建由其他值组合而成的值)如果您要使用按位 and,它就没有多大意义。

它的用法如下:

[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)

本质上,您可以测试是否设置了enum 中的某些位;在这种情况下,我们正在测试是否设置了对应于 Read 的位。值 ReadReadWrite 都将通过此测试(都设置了位零); 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

第二个问题:

我认为当您说“和/或”时,您的意思是“一个、另一个或两者”。这正是 ||(或运算符)所做的。要说“一个或另一个,但不是两个”,您将使用 ^(异或运算符)。

真值表(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)

关于c# - 按位或 | 是什么意思运营商呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/612072/

相关文章:

javascript - 带有 ES6 的 Javascript 中的枚举

enums - 如何使 CRMSvcUtil.exe 生成不重复、无错误的早期绑定(bind)选项集?

C# 对象数组 - 条件验证

.net - 包装Log4net时如何记录MethodName?

python-3.x - 有没有一种简单的方法可以循环迭代枚举?

c# - 无法将类型 'bool?' 隐式转换为 'bool' 。存在显式转换(您是否缺少转换?)

javascript - 添加了 RegisterStartupScript() 的脚本什么时候执行?

c# - VS 2013 Professional Update 4 中无法再打开 .cs 文件

c# - 如何让 Visual Studio 2017 编辑器支持不同的编码风格?

c# - 可以在字符类中使用.NET RegEx向后引用来排除以前匹配的字符吗?