开发者

Using operators & | on enums in C#?

I have an enum in my application to represent the saving options where the user can save the image with lines drawn, circl开发者_如何学运维es, rectangles or any combination, so I declared an enum to represent the saving option.

enum SaveOption{lines,circles,rectangles};

How can I use operators to;

  • Add option to the options
  • Remove option from the options


Mark the enum with the [Flags] attribute, and give each possible value a unique bit value:

[Flags]
enum SaveOption
{
    lines = 0x1,
    circles = 0x2,
    rectangles = 0x4
}

Then you can do this sort of thing:

SaveOption options;

option = SaveOption.lines | SaveOption.circles; // lines + circles
option |= SaveOptions.rectangles; // now includes rectangles
option &= ~SaveOptions.circles; // now excludes circles

Finally for ref, each option must have a value that is represented by a single bit, so in hex that's 0x1, 0x2, 0x4, 0x8, then 0x10, 0x20, 0x40, 0x80 etc. Which is easier to remember than 1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536. Which is as far as I remember :)


To start with, you'd need to specify values which worked in a bitwise fashion. You'd also be best to decorate the enum with FlagsAttribute. Following naming conventions, you'd also rename it to be plural. You'd end up with:

[Flags]
enum SaveOptions
{
    None = 0,
    Lines = 1,
    Circles = 2,
    Rectangles = 4
}

You can then do:

SaveOptions foo = SaveOptions.Lines | SaveOptions.Rectangles;

and similar bitwise operations.

The FlagsAttribute will change how the enum values are converted to and from strings. It's not actually required in order to get the bitwise operations to work, but it's definitely a strong convention, and a generally good idea.


Use the Flags attribute. Don't forget to specify unique bitwise values for each member of the enum:

[Flags]
enum SaveOption
{
    lines = 1,
    circles = 2,
    rectangles = 4
}


You need a cast:

(SaveOption) (lines | circles)

or

SaveOption option = (SaveOption) (lines | circles);

(SaveOption) ((option & ~lines) | rectangle)

You also need to assign bit values to the enum members (as in some of the other answers).

Note: I've left off some C# syntax, and this applies to .Net 2, later version may have cleaned up this syntax.


As for manipulating the flags;

[Flags]
public enum SaveOption
{
    Lines = 1,
    Circles = 2,
    Rectangles = 4
}

static void Main(string[] args)
{
    SaveOption option = SaveOption.Circles | SaveOption.Rectangles;

    Console.WriteLine( option );

    option -= SaveOption.Circles;

    Console.WriteLine( option );

    option = option | SaveOption.Lines;

    Console.WriteLine(option);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜