开发者

Effective enums use

I read a book where the author does this:

public enum Move
{ 开发者_开发问答 
    normal            = 0,
    swim              = 1 << 0,
    crawl             = 1 << 1,
    creep             = 1 << 3,
    jump              = 1 << 3,
    fly               = 1 << 4,
    grapple           = 1 << 5,
    goes_through_door = 1 << 6
}  

Why would you do that, why not just let them have default values like 0,1,2,3...


This is a enum where the values are usable with bitwise operators. It allows for an enum value to be a combination of multiple values. For example

Move crawlAndSwim = Move.crawl | Move.swim;

Bitwise operators can then be used to check for the presence or absence of certain values

if (0 != (aMoveValue & Move.crawl)) {
  // It's crawling
}

if (0 != (aMoveValue & Move.swim)) {
  // It's swiming
}

Wikipedia has a nice article on this subject which may be of interest to you

  • http://en.wikipedia.org/wiki/Bit_field

Note: As casperOne pointed out, this type of enum definition should be annotated with FlagsAttribute to denote it's a flags / bitfield vs a normal one.


Its so that you can combine them with bit-wise operators. I'm not sure that makes total sense with Move, but it makes sense with other things.


It has to do with masks. This way you can represent if it can crawl and swim by a=(crawl | swim). Then you can check the individuals by a&swim.


Because you can use an enum type as flags.

That means you can combine some enum values of the definition into one variable.


<< is a (edit)left-shift operator.

He does this so he can combine multiple values of Move using bitwise operators, though the names are a bit of a bad example.

Lets say I have

public enum VehicleType{
  Car = 1<<0,
  Van = 1<<1,
  Truck = 1<<2
}

Now I want to make a method Depot.RetrieveVehicles(VehicleType type);

Because the values are set out in this fashion, I can do

Depot.RetrieveVehicles(VehicleType.Car | VehicleType.Van); 

To retrieve vehicles that are either a Car or a Van.

So Car (001) | Van (010) gives you 011 in binary.

Just to clear it up a little, I could also do this:

public enum VehicleType{
  Car = 1, //001
  Van = 2, //010
  Truck = 4//100
}

You cannot do this easily if you had just used 0,1,2. You would have to call that method twice.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜