在 Windows Forms 中检查 DrawItemState 等价性的条件表达式是什么意思?

What is the meaning of the conditional expression for checking DrawItemState equivalence in Windows Forms?

我在阅读 DrawItemState documentation 时遇到了以下代码片段:

if ((e.State & DrawItemState.Selected) == DrawItemState.Selected )
          brush = SystemBrushes.HighlightText;

文档中给出了以下解释

Since state can be a combination (bit-flag) of enum values, you can't use "==" to compare them

但是我仍然不明白这个条件表达式与下面显示的片段有何不同:

if (e.State == DrawItemState.Selected )
          brush = SystemBrushes.HighlightText;

此外,我不明白按位与 & 运算符有何不同,以及为什么它甚至包含在条件表达式中。

由于枚举的基础值,您可以设置多个值(bitwise combination):

var state = DrawItemState.Disabled | DrawItemState.Grayed;

这意味着这些都将 return false:

Console.WriteLine(state == DrawItemState.Disabled);  // false
Console.WriteLine(state == DrawItemState.Grayed);    // false

测试值的一种方法是使用按位 "and" 运算符:

Console.WriteLine((state & DrawItemState.Grayed) == DrawItemState.Grayed);  // true

基本上,在我的示例中,state 设置了两个位 - "Grayed" 和 "Disabled"。通过对 "Grayed" 的值使用按位 "and" 运算符,结果也是 "Grayed".

的值
0 0 0 0 0 0 0 0 1 1 0    // binary value of disabled and grayed

0 0 0 0 0 0 0 0 0 1 0    // binary value of grayed

0 0 0 0 0 0 0 0 0 1 0    // result is same value as grayed

您也可以测试多个标志:

Console.WriteLine((state & (DrawItemState.Grayed | DrawItemState.Disabled))
                  == (DrawItemState.Grayed | DrawItemState.Disabled));  // true

0 0 0 0 0 0 0 0 1 1 0    // binary value of disabled and grayed

0 0 0 0 0 0 0 0 1 1 0    // binary value of disabled and grayed

0 0 0 0 0 0 0 0 1 1 0    // result is same value as disabled and grayed

就个人而言,我认为使用 HasFlag:

来测试标志值更容易
Console.WriteLine(state.HasFlag(DrawItemState.Grayed));  // true

请注意,如果只有一个值,则 == 会起作用,但对于支持按位组合的 "flags" 枚举,这永远无法保证。

var state = DrawItemState.Grayed;

Console.WriteLine(state == DrawItemState.Grayed);  // true