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/