C#:枚举位运算符(自定义授权的MVC) [英] C#: bitwise operator in enum (Custom Authorization in MVC)

查看:396
本文介绍了C#:枚举位运算符(自定义授权的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?

如。如果我想与客户,员工,主管和管理4级证券。

eg. If I want to have 4 level securities 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?

非常感谢你。

陈道明

推荐答案

本例使用按位移位运算符:&LT;&LT;。这个操作符取位和移动它们。例如,1所述; 3;的结果中的8号因此,在二进制

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

if语句你是为了告诉别人是否有一个特定的角色。它采用按位与&放大器;。按位与结合了两个号码,仅设置如果该位被两个操作数设置一个位。

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.

这篇关于C#:枚举位运算符(自定义授权的MVC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆