![](/img/trans.png)
[英]Is there a solution for a bitwise logical AND (&) operator between two Enum values in C#
[英]C#: bitwise operator in enum (Custom Authorization in MVC)
我目前正在閱讀一篇文章 ,但我真的不明白這是如何與邏輯運算符一起工作的。 任何人都可以向我解釋這個嗎?
例如。 如果我想與客戶,員工,主管和管理員有4級證券。
[Serializable]
[Flags]
public enum WebRoles
{
customer= 1 << 0,
employee= 1 << 1,
supervisor = 1 << 2,
Admin = 2 << 3
}
然后我應該如何實現以下邏輯。
if (Roles != 0 && ((Roles & role) != role))
return false;
有人能為我提供一些這方面的知識嗎?
非常感謝你。
道明
他們使用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
和Supervisor
,只需設置相應的位。
以及如何檢查是否設置了一個位? 這正是(Roles & role) != role)
做的。 例如:
WebRoles user = WebRoles.Employee | WebRoles.Supervisor;
bool isEmployee = (user & WebRoles.Employee) == WebRoles.Employee; // true
如果測試用戶變量以檢查是否設置了Employee
位,則該&
運算符將返回所有匹配位。
希望這有幫助; 隨時編輯這個答案
此示例使用按位移位運算符:“<<”。 該運算符獲取位並移位它們。 例如,“1 << 3”會產生數字8.因此,在二進制中,
customer = 0001
employee = 0010
supervisor = 0100
admin = 1000 (I think this was supposed to read 1 << 3)
現在,您可以使用按位或運算符為人員分配多個角色。 這將是一個單豎線“|”。 逐位或逐位組合兩個數字,設置在兩個操作數中的任何一個中設置的每個位。
myRole = customer | employee = 0011
您擁有的if語句旨在告訴某人是否具有特定角色。 它使用按位和:“&”。 按位 - 並組合兩個數字,只有在兩個操作數中都設置了該位時才設置一個位。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.