用户可以拥有以下访问权限:
Read = 1
Create = 2
Edit = 4
Delete = 8
Publish = 16
Administer = 32
当访问权限保存在数据库中时,只有一个数字用于表示该用户的所有访问权限。
e.g。
3 = Read + Create
25 = Read + Delete + Publish
如何获取给定号码(访问掩码)的所有访问权限?
非常感谢任何帮助!
答案 0 :(得分:9)
[Flags]
public enum MyFlags
{
Read = 1,
Create = 2,
Edit = 4,
Delete = 8,
Publish = 16,
Administer = 32,
}
申报
MyFlags readCreate = MyFlags.Read | MyFlags.Create;
测试
bool hasRead = (readCreate & MyFlags.Read) == MyFlags.Read;
bool hasEdit = (readCreate & MyFlags.Edit) == MyFlags.Edit;
答案 1 :(得分:4)
var mask = (AccessRights)25;
var rightsForMask = Enum.GetValues(typeof(AccessRights))
.Cast<AccessRights>()
.Where(x => mask.HasFlag(x));
foreach (var right in rightsForMask)
{
// displays "1:Read", "8:Delete", "16:Publish"
Console.WriteLine((int)right + ":" + right);
}
// ...
[Flags]
public enum AccessRights
{
Read = 1, Create = 2, Edit = 4, Delete = 8, Publish = 16, Administer = 32
}
如果您不使用.NET4,则HasFlag
方法将不可用,在这种情况下,您需要将Where
子句更改为Where(x => (mask & x) == x)
。< / p>