开发者

C#: bitwise operator in enum (Custom Authorization in MVC)

I'm currently reading an article , but I do not really understand how this work with the logical operator. Can anyone explain this to me?

eg. If I want to have 4 level securities开发者_JS百科 with customer, employee, supervisor and Admin.

[Serializable]
[Flags]
public enum WebRoles
{             
    customer= 1 << 0,
    employee= 1 << 1,
    supervisor = 1 << 2,
    Admin = 2 << 3
}

and then how I should implement the following logic.

if (Roles != 0 && ((Roles & role) != role))
            return false;

Can anyone provide me some knowledge of this implementation?

Thank you very much.

Daoming


They're using an enum as a bit map: if a specific bit is set, so you have that privilege. They're also using a left shift operator. Let me try to demonstrate all that at once:

Role         Decimal   Binary   Shifted   Decimal
--------     -------   ------   -------   -------
Customer   =    1    = 000001 = 000001  =    1
Employee   =    1    = 000001 = 000010  =    2
Supervisor =    1    = 000001 = 000100  =    4
Admin      =    2    = 000010 = 010000  =   16

This way you can combine two roles. For instance, some user can play Employee and Supervisor at same time, just having correspondent bits set.

And how to check if a bit is set? It's exactly what that (Roles & role) != role) do. For example:

WebRoles user = WebRoles.Employee | WebRoles.Supervisor;
bool isEmployee = (user & WebRoles.Employee) == WebRoles.Employee; // true

If you test user variable to check if that Employee bit is set, that & operator will return all match bits.

Hope this help; feel free to edit this answer


This example uses the bitwise shift operator: "<<". This operator takes the bits and shifts them. For example, "1 << 3" results in the number 8. So, in binary,

customer =    0001
employee =    0010
supervisor =  0100
admin =       1000 (I think this was supposed to read 1 << 3)

Now, you can assign people multiple roles using the bitwise-or operator. This would be a single vertical-bar "|". The bitwise or combines the two numbers bit-by-bit, setting each bit that is set in either of the two operands.

myRole = customer | employee = 0011

The if-statement you have is intended to tell whether someone has a particular role. It uses bitwise-and: "&". Bitwise-and combines the two numbers, setting a bit only if the bit is set in both the operands.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜