使用运算符和| 在C#的枚举?

Sar*_* S. 3 c# enums

我的应用程序中有一个用于表示保存选项的枚举,用户可以使用绘制的线条,圆形,矩形或任意组合保存图像,因此我声明了一个枚举来表示保存选项.

enum SaveOption{lines,circles,rectangles};
Run Code Online (Sandbox Code Playgroud)

我怎样才能使用运算符;

  • 添加选项选项
  • 从选项中删除选项

Kie*_*one 15

使用[Flags]属性标记枚举,并为每个可能的值赋予唯一的位值:

[Flags]
enum SaveOption
{
    lines = 0x1,
    circles = 0x2,
    rectangles = 0x4
}
Run Code Online (Sandbox Code Playgroud)

然后你可以做这样的事情:

SaveOption options;

option = SaveOption.lines | SaveOption.circles; // lines + circles
option |= SaveOptions.rectangles; // now includes rectangles
option &= ~SaveOptions.circles; // now excludes circles
Run Code Online (Sandbox Code Playgroud)

最后,对于裁判,每个选项必须由单个位表示的值,所以在六角这是0x1,0x2,0x4,0x8,然后0x10,0x20,0x40,0x80等这是很容易,1,2,4,8,16,32记住, 64,128,256,512,1024,2048,4096,8192,16384,32768,65536.这是我记得的:)