c# - 这个语句在 C# 中是什么意思?

标签 c# if-statement

if ((a & b) == b) 在下面的代码块中是什么意思?

if ((e.Modifiers & Keys.Shift) == Keys.Shift)
{
    lbl.Text += "\n" + "Shift was held down.";
}

为什么不是这样呢?

if (e.Modifiers == Keys.Shift)
{
    lbl.Text += "\n" + "Shift was held down.";
}

最佳答案

如果你看一下Keys enum , 这是 flag enum带有 [FlagsAttribute] 属性。

Use the FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value.

Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap.

所以 e.Modifiers 可能是多个枚举的组合:

e.Modifiers = Keys.Shift | Keys.Cancel | Keys.Enter

只是非常简单的假设来解释这个概念:

Keys.Shift  : 001 (1)
Keys.Cancel : 010 (2)
Keys.Enter  : 100 (4)

所以:

e.Modifiers = Keys.Shift | Keys.Cancel | Keys.Enter equal 001 | 010 | 100 = 111

条件:

    e.Modifiers & Keys.Shift equal 111 & 001 = 001

意思是:

 e.Modifiers & Keys.Shift == Keys.Shift

如果 e.Modifiers 不包含 Keys.Shift:

e.Modifiers = Keys.Cancel | Keys.Enter (110)

所以结果会是:

e.Modifiers & Keys.Shift equals 110 & 001 = 000 (is not Keys.Shift)

总结一下,这个条件检查e.Modifiers是否包含Keys.Shift

关于c# - 这个语句在 C# 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16063518/

相关文章:

c# - IIS使用OpenXML创建的word文件处置后继续被IIS锁定

c++ - 检查 if 语句的多个相等/不等式条件

javascript - 在这种特定情况下,if-else 是否比 try-catch 更好,性能明智?哪种方式是最佳做法?

java - if条件中的return语句函数

c# - 文件正在通过 visual studio 下载,而不是通过 .exe 下载

c# - WrapPanel 为每个动态扩展控件创建一个新列

c# - 替换c#中字符串的最后一个字符

c# - Interop.xxxxx.dll 是如何生成的?

python - Pandas 如果其他空

python - 为什么 ... == True 在 Python 3 中返回 False?