c# - 此 C# 运算符在此代码段中如何工作?

标签 c# syntax operators bit-manipulation bitwise-operators

我在 SO 上找到了这个代码片段(抱歉,我没有问题/答案组合的链接)

 bool isDir = (File.GetAttributes(source) & FileAttributes.Directory) == FileAttributes.Directory;

这让我感到困惑,因为 FileAttributes.Directory== 的两边。

在这种情况下,& 做了什么?我不确定如何阅读这行代码。我正在尝试评估路径字符串是文件还是目录。

最佳答案

它使用位掩码来测试是否设置了单个位 (FileAttributes.Directory)。

枚举的值是 2 的幂,对应于各个位。

    ReadOnly = 1,
    Hidden = 2,
    System = 4,
    Directory = 16,
    Archive = 32,
    Device = 64,

如果设置了 ReadOnly 和 Directory,则 FileAttributes 等于 17。二进制计算如下所示:

File.GetAttributes(source) = 00001001   
FileAttributes.Directory   = 00001000 &
-------------------------------------
                             00001000

如果目录位设置,您将得到零:

File.GetAttributes(source) = 00000001   
FileAttributes.Directory   = 00001000 &
-------------------------------------
                             00000000

编写给出相同效果的表达式的一种稍微更简洁的方法是针对零进行测试:

bool isDir = (File.GetAttributes(source) & FileAttributes.Directory) != 0;

关于c# - 此 C# 运算符在此代码段中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4741339/

相关文章:

java - 有什么方法可以在 Java 中生成与在 C# 中生成的 UUID 相同的 UUID?

C# 设置的替代方法是什么

c# - `using` 指令的位置在 C# 中有什么不同吗?

prolog - 斜线(/)在序言中做什么?

python - 将字符串解析为过滤 Pandas 数据框的条件

c# - 创建带有更新下载进度条的 ListView Windows 8 C# XAML

ruby-on-rails - 语法错误 : unexpected $end when using if/else if?

c - 下面的变量声明会导致词法错误还是语法错误?

c++ - 设置声明值时调用函数

c# - "Access to the path ' a-guid.8Event ' is denied."启动时