Why use flags+bitmasks rather than a series of booleans?

后端 未结 10 2098
猫巷女王i
猫巷女王i 2021-02-05 03:29

Given a case where I have an object that may be in one or more true/false states, I\'ve always been a little fuzzy on why programmers frequently use flags+bitmasks instead of ju

10条回答
  •  迷失自我
    2021-02-05 04:16

    From a domain Model perspective, it just models reality better in some situations. If you have three booleans like AccountIsInDefault and IsPreferredCustomer and RequiresSalesTaxState, then it doesnn't make sense to add them to a single Flags decorated enumeration, cause they are not three distinct values for the same domain model element.

    But if you have a set of booleans like:

     [Flags] enum AccountStatus {AccountIsInDefault=1, 
             AccountOverdue=2 and AccountFrozen=4}
    

    or

      [Flags] enum CargoState {ExceedsWeightLimit=1,  
             ContainsDangerousCargo=2, IsFlammableCargo=4, 
             ContainsRadioactive=8}
    

    Then it is useful to be able to store the total state of the Account, (or the cargo) in ONE variable... that represents ONE Domain Element whose value can represent any possible combination of states.

提交回复
热议问题