Flag enum confusion c #

According to my code a = 1, b = 2, c = 3, etc. I thought the flag would do a = 1, b = 2, c = 4, etc.

[Flags]
public enum someEnum { none, a, b, c, d, e, f, }

How to get what I intended (c = 4, e = 8)? and what does the [Flags]above mean ?

+3
source share
4 answers

You can specify values ​​for enumerations, this is necessary for flags:

[Flags]
enum MyFlags {
  Alpha=1,
  Beta=2,
  Gamma=4,
  Delta=8
}

What does [Flags] mean?

This means that the runtime will support bitwise operations on values. It does not matter for the values ​​that the compiler generates. For example. if you do it

var x = MyFlags.Alpha | MyFlags.Beta;

with the Flags attribute, the result x.ToString()is " Alpha, Beta". Without an attribute, this will be 3. Also changes the behavior of the parsing.

EDIT: , , non-flags, , # 3 4 ( ).

+17

Flags , ; .

+1

Flags / ToString(), Parse() IsDefined() .

Flags, .

( ) .

+1

[Flags] , , , , , .

It also does not change the bitwise operations that the compiler will allow for enumeration.

What he does is change the behavior of the methods Enum.Parseand Enum.ToStringto support combinations of values ​​as well as single values, for example. "a, b, c".

0
source

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


All Articles