Using bitwise operations in C # For permission management
Abstract: This article explains how to use the C # bitwise Operation to implement permission management. When designing the permission, convert the permission management operation to the C # bitwise operation for processing.
Tags: C # bit operation permission management
Common bitwise operations include (&), (|), and (~), For example:
1 & 0 = 0, 1 | 0 = 1 ,~ 1 = 0
When designing a permission, we can convert the permission management operation to a C # bitwise operation.
Step 1: Create an enumeration to indicate all permission management operations:
///
TestCode
[Flags]
Public Enum Permissions
{
Insert = 1,
Delete = 2,
Update = 4,
Query = 8
}
[Flags] indicates that this enumeration can support the C # bitwise operation. For each enumerated value, we use the Npower of 2 to assign a value. In this way, when it is binary, it is exactly 1 = 0001, 2 = 0010, 4 = 0100, 8 = 1000, etc. Each digit indicates a permission. 1 indicates that the permission is granted, and 0 indicates that no.
Next is the permission calculation:
1. Permission addition, which can be implemented using and operations. We know that 0001 | 0100 = 0101 means that permissions with the first and third places are managed at the same time, and enumeration means:
Permissions permissions = permissions. Insert | permissions. Update
2. Permission Subtraction is implemented by operations + non-operations. To remove the insert permission, perform the following operations:
Permissions permissions & = ~ Permissions. Insert means 0101 &~ 0001 = 0101 & 1110 = 0100
3. when determining whether a user has the permission for this operation, the user's permission and operation permission should be performed and calculated, if the result is still operation permission management, the user has this permission:
Permissions permissions = permissions. Insert | permissions. update;
Assert. istrue (permissions & permissions. insert) = permissions. insert );
Assert. istrue (permissions & permissions. Update) = permissions. Update );
Assert. isfalse (permissions & permissions. query) = permissions. query );
Permissions & = ~ Permissions. Delete;
Assert. isfalse (permissions & = ~ Permissions. delete) = permissions. delete );
When the comparison process is 0101 & 0001 = 0001,000, the 0 bits of 1 are set to 0 with the C # bits, and the 1 bits are compared.