为什么许多WPF类将布尔值存储为枚举标志?

Her*_*ton 3 c# wpf boolean coding-style enum-flags

如果您反思WPF System.Windows.Controls.Control类,您可以看到:

public class Control : FrameworkElement
{ 
    internal ControlBoolFlags _controlBoolField;
    // [...]
    internal bool ReadControlFlag(ControlBoolFlags reqFlag);
    internal void WriteControlFlag(ControlBoolFlags reqFlag, bool set); 
    // I think it's clear what they do
    // [...]
    internal enum ControlBoolFlags : ushort
    {
        CommandDisabled = 8,
        ContainsSelection = 128,
        ContentIsItem = 16,
        ContentIsNotLogical = 1,
        HeaderIsItem = 32,
        HeaderIsNotLogical = 4,
        IsSpaceKeyDown = 2,
        ScrollHostValid = 64,
        VisualStateChangeSuspended = 256
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我只想知道为什么MS选择这种方式来存储布尔值而不是bool为每个标志使用一个字段.它只是他们的编码风格,他们只是想为每个领域节省空间吗?

Joh*_*aft 6

有几个原因.一对夫妇包括:

  • 这是一个巨大的节省空间.1个短代表许多(本例中为9个)可能性.这是单个ushort的大小,而不是许多bool
  • 您可以将所有这些值传递给单个参数中的方法,而不是具有许多参数和一堆重载方法.