Original article: Dig a series of things that are not commonly used in C # (5) -- flagattribute
Speaking of flagsattribute, I saw a short piece of code a few days ago, which probably means to return which delivery methods are available based on the flight policy and whether these methods are available.
To hide or enable the relevant delivery methods on the interface. If you book a ticket, you may know that there are many delivery methods, such as "No need to print a route ticket (pjn)" and "airport pick-up) ",
"Local Delivery (CND)", "express delivery (EMS)", and so on.
According to the above logic, there are two delivery modes available and unavailable. In terms of logical implementation, it is easy to think of bit, each digit represents a delivery method,
0 indicates unavailability, and 1 indicates availability. Therefore, you only need to give a number to the flight interface. I only need to determine which bit is 1.
For example, the 8-bit byte field is used as an example:
As you can see, express delivery (EMS) is not available, so how to judge it, in fact, 17 & 32 is OK, if it is 32, it indicates available, 0 is not available, others
You can use the same method.
The Code logic we saw last time is like this, but after all, in a team, the level is uneven and it is easy to understand with pure numbers. If
With enumeration, it may be more perfect.
Speaking of enumeration, it is actually the syntactic sugar that the compiler gives us. In essence, it is a const field inherited under the enum type. Since it is a const
It is born with regular mathematical operations such as (+,-, *,/^, |.
For example:
1 [Flags] 2 enum Deliver : byte 3 { 4 CND = 0x01, 5 PJS = 0x02, 6 SND = 0x04, 7 PJN = 0x08, 8 Airport = 0x16, 9 EMS = 0x3210 }
Then look at the above Enum generated il code.
Someone may ask, what is the "uint8" here? In fact, this is the real primitive type hidden behind the enumeration type, which can be obtained using getunderlyingtype.
Generally, an enumeration can only display one State. If you want the enumeration to display multiple states, you can use flagattribute to mark the enumeration so that the flag can process the enumeration,
To provide powerful combination functions.
For example, according to the number 17 returned by the flight policy, we know that airport and CND are available. If flagattribute is used for marking, we don't have to worry about it this time.
You can directly convert 17 to enumeration.
As you can see, after enumeration conversion, you may understand the programmer and record the log to facilitate analysis and tracking.