How to save several states in one variable?

My object Itemhas several binary states that can be combined

bool CanBeSold;
bool CanBeBought;
bool CanBeExchanged;

I need to save the current combination of values ​​into one variable. The reason that I need to save this value in the database. In C ++, I would create a bitmask where one state takes a bit. Is this good practice in .NET?

+3
source share
4 answers

You can use an enumeration with an attribute Flags:

[Flags]
enum MyStates {
  CanBeSold = 1,
  CanBeBought = 2,
  CanBeExchanged = 4
}

Since enums are integer data types, you can combine them in the usual way:

state = MyStates.CanBeSold | MyStates.CanBeExchanged

, , enum ( Doug Ferguson ), , t , .

:

 CanBeSoldOrBought = CanBeSold | CanBeBought

 CanBeSoldOrBought = 3

, . , , , ReadWrite Read Write.

, . .

-

if ((state & MyStates.CanBeSold) != 0) { ... }
+13

, . Flags .

[Flags]
public enum CanBe {
  Sold = 1,
  Bought = 2,
  Exchanged = 4
}

:

CanBe can = CabBe.Sold | CanBe.Exchanged.

| =:

can |= CanBe.Sold;

:

can |= CanBe.Sold | CanBe.Bought;

& =:

can &= CanBe.Sold;

:

can &= CanBe.Sold | CanBe.Bought;

~, :

can &= ~CabBe.Bough;

:

can &= ~(CabBe.Bough | CanBe.Exchanged);

:

if ((can & CanBe.Sold) != 0) ...

:

if ((can & (CanBe.Sold | CanBe.Bought)) != 0) ...

, :

if ((can & (CanBe.Sold | CanBe.Bought)) == (CanBe.Sold | CanBe.Bought)) ...
+7

- .NET .

public enum ItemState { CanBeSold = 1; CanBeBought = 2; CanBeExchanged = 4 }

if (item.State ^ ItemState.CanBeSold) ....
+2

Flags

[Flags]
enum MyStates {
    CanBeSold = 0x1,
    CanBeBought = 0x2,
    CanBeExchanged = 0x4,
}

MyStates m_Flags;

// to set a flag:
m_Flags |= MyStates.CanBeSold;

// to unset a flag:
m_Flags &= ~MyStates.CanBeSold;
+2

Source: https://habr.com/ru/post/1724859/


All Articles