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)& 表示"结果是操作数两侧出现的所有属性"所以它基本上充当了一个掩码 - 只保留那些出现在("除了系统之外的所有东西")的属性.一般来说:
|=只会向目标添加位&=只会从目标中删除位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 = 0和1 & x = x任何x