什么是| =(单管道相等)和&=(单个&符号相等)的意思

Sil*_*ght 96 c# operators bitwise-operators

在以下行中:

//Folder.Attributes = FileAttributes.Directory | FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReadOnly;
Folder.Attributes |= FileAttributes.Directory | FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReadOnly;


Folder.Attributes |= ~FileAttributes.System;
Folder.Attributes &= ~FileAttributes.System;
Run Code Online (Sandbox Code Playgroud)

在C#中,|=(单管道相等)和&=(单个&符号相等)是什么意思
我想删除系统属性并保留其他属性...

Jon*_*eet 132

他们是复合赋值运算符,翻译(非常松散)

x |= y;
Run Code Online (Sandbox Code Playgroud)

x = x | y;
Run Code Online (Sandbox Code Playgroud)

同样的&.在一些关于隐式演员的案例中有更多的细节,目标变量只被评估一次,但这基本上是它的要点.

就非复合运算符而言,&是按位"AND"并且|是按位"OR".

编辑:在这种情况下你想要Folder.Attributes &= ~FileAttributes.System.要理解原因:

  • ~FileAttributes.System表示" 除了 System " 之外的所有属性(~是按位NOT)
  • & 表示"结果是操作数两侧出现的所有属性"

所以它基本上充当了一个掩码 - 保留那些出现在("除了系统之外的所有东西")的属性.一般来说:

  • |=只会向目标添加
  • &=只会从目标中删除

  • `x = x | (y);` 是一种更好的描述方式,因为 `x |= y + z;` 与 `x = x | 不同。y + z;` (2认同)

Arm*_*yan 31

a |= b相当于a = a | b除了a仅被评估一次
a &= b相当于a = a & b除了a仅被评估一次之外

要在不更改其他位的情况下删除系统位,请使用

Folder.Attributes &= ~FileAttributes.System;
Run Code Online (Sandbox Code Playgroud)

~是按位否定.因此,除了系统位之外,您将所有位设置为1.and与面罩-ing将系统设置为0,并将所有其他位不变,因为0 & x = 01 & x = x任何x

  • `a` 只计算一次是什么意思?为什么它会被评估更多次? (2认同)
  • @Polluks:我无法理解你对一个和两个管道的评论 - 我认为使用两个管道而不是一个管道是Silkfire在[最后评论](/sf/ask/485973421/#comment95263986_6942502)中的全部观点。另外,我不相信“除了‘a’只评估一次’的说法确实指的是短路评估,因为短路评估不会改变*第一个*操作数(`a`)的评估,但可能会跳过*第二个*操作数(`b`)的计算。 (2认同)