开发者

Enum programming issue

开发者 https://www.devze.com 2023-04-03 04:23 出处:网络
I have a code like enum WeekDays { Sat = 64, Sun = 1, Mon = 2, Tue = 4, Wed = 8, 开发者_开发问答Thu = 16,

I have a code like

enum WeekDays
{
    Sat = 64,
    Sun = 1,     
    Mon = 2,
    Tue = 4,
    Wed = 8,
 开发者_开发问答   Thu = 16,
    Fri = 32
    WorkDays = Sat | Sun | Mon | Tue | Wed 
}

I would like to know more about:

WorkDays = Sat | Sun | Mon | Tue | Wed 

What does its value mean?


You probably have a [Flags] attribute above that.

Workdays is created as the binary-or of the working day values (not my working days).

So the days are manually numbered to make them powers of 2 :

Sun  = 0000001
Mon  = 0000010
Tue  = 0000100
Wed  = 0001000
Sat  = 1000000

etc

And then you can use binary operators to do Set operations:

MyWeekend = Sat | Sun;  // 1000000 | 0000001 = 1000001

and use the binary-and to test membership:

WeekDays d = ...;
if ((d & MyWeekend) != 0)
{
    // it's weekend !
}


You can use WorkDays to test whether given day is work day:

WeekDays d = ... ;   // set some value

if ( d & WeekDays.WorkDays )
{
    // d is work day
}

Of course, enumeration should be marked as Flags, as already mentioned in another answers.


its an bit OR operator. So your Workdays will have a value between 1 and 64 (representing every combination of the week). Suppose you work 3 days in a week, say Sun, Mon and Tue.

Then your workdays will be Sun| Mon | Tue (which is 7).

In Binary operation: Sun - 0000 0001 Mon - 0000 0010 Tue - 0000 0100

Bit Or - 0000 0111

So each value between 1 to 64 will represent every possible combination of the week.


It ORs the values together => | is the OR operator.

If used like this inside enums, you are using "Flags", or "Bitfields" that can be used to store combinations of values. You can read more about this eg. here: http://msdn.microsoft.com/en-us/library/ms229062(v=VS.100).aspx


enum WeekDays
{
Sat = 64, //value in binary = 1000000
Sun = 1,  //value in binary = 0000001     
Mon = 2,  //value in binary = 0000010
Tue = 4,  //value in binary = 0000100
Wed = 8,  //value in binary = 0001000
Thu = 16, //value in binary = 0010000
Fri = 32  //value in binary = 0100000

WorkDays = Sat| Sun | Mon | Tue | Wed //binary or of sat-wed = 1001111
}
0

精彩评论

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

关注公众号