C#:枚举中的位运算符(MVC中的自定义授权)
我目前正在阅读,但我不太明白这是如何与逻辑运算符一起工作的。谁能给我解释一下吗 如果我想与客户、员工、主管和管理员建立4级证券C#:枚举中的位运算符(MVC中的自定义授权),c#,asp.net-mvc,operators,C#,Asp.net Mvc,Operators,我目前正在阅读,但我不太明白这是如何与逻辑运算符一起工作的。谁能给我解释一下吗 如果我想与客户、员工、主管和管理员建立4级证券 [Serializable] [Flags] public enum WebRoles { customer= 1 << 0, employee= 1 << 1, supervisor = 1 << 2, Admin = 2 << 3 } 有人能给我提供一些关于这
[Serializable]
[Flags]
public enum WebRoles
{
customer= 1 << 0,
employee= 1 << 1,
supervisor = 1 << 2,
Admin = 2 << 3
}
有人能给我提供一些关于这个实现的知识吗
多谢各位
Daoming此示例使用按位移位运算符:“他们使用
enum
作为位图:如果设置了特定位,则您拥有该权限。他们还使用左移位运算符。让我尝试一次演示所有这些:
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
如果测试用户变量以检查是否设置了Employee
位,则&
运算符将返回所有匹配位
希望有帮助;请随意编辑此答案。您似乎对“逻辑”和“按位”运算符的含义感到困惑。使用错误的术语将使您更难找到正确的信息。@Anon,谢谢。我现在明白了。
customer = 0001
employee = 0010
supervisor = 0100
admin = 1000 (I think this was supposed to read 1 << 3)
myRole = customer | employee = 0011
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
WebRoles user = WebRoles.Employee | WebRoles.Supervisor;
bool isEmployee = (user & WebRoles.Employee) == WebRoles.Employee; // true