What is a bitwise operation
The commonly used bit operations are mainly with (&), or (|) and non-(~), such as:
1 & 00 = 00;2 01 | 00 = 01;3 ~01 = 0 0;
use in the Authority design
Create an enumeration to represent all rights management operations:
1 [Flags] 2 public enum Permissions 3 {4 Insert = 1, 5 Delete = 2, 6 Update = 4, 7 Query = 8 8}
[Flags] Indicates that the enumeration can support C # bit operations.
Enumeration of each item value, we use 2 of the N-square to assign the value, so that the binary is exactly 1 = 0001, 2 = 0010, 4 = 0100, 8 = 1000, and so on.
Each one represents a permission, 1 indicates a permission, and 0 means no.
Next is the operation of the permission:
1. The addition of permissions, use and operation to achieve.
0001 | 0100 = 0101, which indicates that permissions are managed with both first and third bits, and the enumeration is represented as:
1 Permissions per = Permissions.insert | Permissions.update
2. The subtraction of permissions, using and operation + non-operation to achieve.
If you want to remove the Insert permission above, the action is:
1 Permissions per &= ~permissions.insert2//That is 3 0101 & ~0001 = 0101 & 1110 = 0100
3. Authority judgment, use and operation.
To determine whether there is permission to operate, the user's permissions and operation permissions and operations, if the result is still operation Rights Management, it means that the user has this permission:
1 Permissions per = Permissions.insert | Permissions.update; 2 if (per & permissionspermissions.insert = Permissions.insert) 3 {4//with Operation Rights 5}
The comparison process is 0101 & 0001 = 0001, 0001 of 0 bits are used with C # bitwise operations to set the other bits to 0, which becomes only 1 of this bit.
Summarize
We've talked about 3 different ways to do this:
Assigning permissions, removing permissions, and judging the inclusion of permissions. So that one of our authority design is basically satisfied. In fact, in the MSSQL these relational databases also support bit operations.
Sometimes, such as the order table, need a lot of state, if the design of a state is the flow state down. You can use "bit" to design this state preservation method. And because the database supports bit operations, we can also easily filter the data as we query the results.
C # Learning Note-----bit operation permission Assignment in C # enumeration