菜单权限场景,通过枚举,添加/移除某个权限,判断是否也有该权限
AuthorityEnums:
注意:枚举值设置为2的幂,防止值冲突
[Flags]
public enum AuthorityEnums
{
Authority_01 = 1, //权限1
Authority_02 = 2, //权限2
Authority_03 = 4, //权限3
Authority_04 = 8 //权限4
}
program:
static void Main(string[] args)
{
//模拟数据库当前权限总和
int allAuthority = (int)(AuthorityEnums.Authority_01 | AuthorityEnums.Authority_04);
//是否拥有权限
bool isAuthority = IsAuthority(allAuthority, (int)AuthorityEnums.Authority_01);
Console.WriteLine($"是否拥有权限1:{isAuthority}");
isAuthority = IsAuthority(allAuthority, (int)AuthorityEnums.Authority_02);
Console.WriteLine($"是否拥有权限2:{isAuthority}");
isAuthority = IsAuthority(allAuthority, (int)AuthorityEnums.Authority_04);
Console.WriteLine($"是否拥有权限4:{isAuthority}");
//添加权限
int result = SetAuthority(allAuthority, 1, (int)AuthorityEnums.Authority_03);
Console.WriteLine($"当前权限:{result}");
result = SetAuthority(allAuthority, 0, (int)AuthorityEnums.Authority_01);
Console.WriteLine($"当前权限:{result}");
Console.ReadKey();
}
///
/// 设置权限
///
/// 现有权限总和
/// 取消或设置操作(0取消,1设置)
/// 设置操作对应的状态值
///
public static int SetAuthority(int AllAuthority, int Action, int currentAuthority)
{
int NewStatus = AllAuthority;
if (Action == 1)
{
//判断此权限串是否拥有相应操作,不包括时加入权限
if ((AllAuthority & currentAuthority) <= 0)
{
NewStatus = AllAuthority | currentAuthority;
}
}
else
{
//判断此权限串是否拥有相应操作,有权限时移除权限
if ((AllAuthority & currentAuthority) > 0)
{
NewStatus = AllAuthority & ~currentAuthority;
}
}
return NewStatus;
}
///
/// 判断是否拥有权限
///
/// 现有权限总和
/// 查询权限值
///
public static bool IsAuthority(int AllAuthority, int currentAuthority)
{
if ((AllAuthority & currentAuthority) == currentAuthority)
{
return true;
}
return false;
}
输出:
如果有这样需求:需要查询某个权限的所有用户,sql语句怎么写?
oracle语法:bitand(位与)、bitor(位或)
查询拥有Authority_03 权限的所有用户
select * from user where bitand(roles,1)=4;
查询拥有Authority_03 和Authority_01 权限的所有用户
select * from user where bitand(roles,1)=5;