If you are not clear about bitwise operations, you can read my article, "foundation is the top priority ~ Bitwise calculation and integer variable bitwise calculation (like Enumeration type)
What we want to do today is to verify the difference between bitwise operations (OR) and addition operations (+) and non-operations (subtraction) and subtraction operations, for an enumeration type marked as the Flags feature and a special numeric type (the n of 2), their bitwise operations will have some features, it is important that we use these features to reduce the complexity of our program design.
In our example, we use an enumerated object FileProperty to describe it. Its definition is as follows:
= = =
Here is the bitwise operation of this object. First, let's look at an OR operation. I prefer to call it an addition bitwise operation:
en =|||| enAdd =++++, en.GetHashCode(), enAdd.GetHashCode());
We can see that the code has been added multiple times. Let's take a look at the results.
Through the above example, we know that during bitwise operations, no matter how many duplicate values you have, only one value is generated during calculation. If you want to know the principle, it can be converted to binary, and the result is not hard to see. (Or operation principle is: two operands, or operation by position, the result is 1 as long as one of the numbers is 1)
| = | = | | =
The following are bitwise AND non-bitwise operations. I prefer to call it a bitwise operation:
en2 =||||= en2 & (~(FileProperty.Read | FileProperty.Read)); Console.WriteLine(, en2);
Result:
If you want to check whether an enumeration object (Flags type) contains an enumeration element, you can use the HasFlag method in. net4.0. Let's take a look.
resultMsg = en + Console.WriteLine(resultMsg, FileProperty.Write,en.HasFlag(FileProperty.Write)); Console.WriteLine(resultMsg, FileProperty.Replace,en.HasFlag(FileProperty.Replace));
Result:
With this feature, we have a job like this to find the attribute types contained in all the files and see the code:
FileID { ; Filename { ; FileProperty FileProperty { ;
List<File> fileList = List<File> File{FileID=,Filename=, FileProperty= File{FileID=,Filename=, FileProperty== = = FileProperty.Read |==>|= + propertyAll);
Result:
Sometimes, a little more knowledge may make the program we designed easier!