C# 用二进制(位运算)控制系统权限
首先,来熟悉一下C#中位运算的操作符
运算符号
|
意义
|
运算对象类型
|
运算结果类型
|
实例
|
~
|
非运算
|
整型,字符型
|
整型
|
~a
|
&
|
与运算
|
a & b
|
||
|
|
或运算
|
a | b
|
||
^
|
异或运算
|
a ^ b
|
||
<<
|
位左移运算
|
a<<4
|
||
>>
|
位右移运算
|
a>>2
|
根据二进制特点,定义每一位表示一个权限,比如二进制“0001”,最后位的1表示可进行插入操作
一个简单权限的枚举
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/// <summary>
/// 位运算,二进制 /// </summary> [Flags] public enum PermissionEnum { /// <summary> /// 初始化 /// 0000 /// </summary> Init = 0, /// <summary> /// 插入 /// 0001 /// </summary> Insert = 1, /// <summary> /// 删除 /// 0010 /// </summary> Delete = 2, /// <summary> /// 更新 /// 0100 /// </summary> Update = 4, /// <summary> /// 查询 /// 1000 /// </summary> Query = 8 } |
添加一个权限的时候,用“或运算”进行添加
添加一个插入权限
1
|
PermissionEnum perm = PermissionEnum.Init | PermissionEnum.Insert;
|
通过“或运算”后,最后perm的值为“0001”,如果再添加一个查询权限,perm值为“1001”,系统通过判断每一位的值来判断是否有权限
删除一个权限的时候,用“与运算”和“非运算”进行操作
1
|
PermissionEnum perm = PermissionEnum(原始的值) & ~PermissionEnum.Delete;
|
比如原始值是0101,那么 0101 & ~0001 = 0101 & 1110 = 0100
以下是位运算操作类
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GSystem.Data.Permission { public class PermissionManager { public static PermissionEnum ConverEnum(string per) { PermissionEnum perm = (PermissionEnum)Enum.Parse(typeof(PermissionEnum), per); return perm; } public static PermissionEnum ConverEnum(int per) { PermissionEnum perm = (PermissionEnum)Enum.Parse(typeof(PermissionEnum), per.ToString()); return perm; } /// <summary> /// 是否有T这个值 /// bool canRead = permissions.Has(PermissionTypes.Read); /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type"></param> /// <param name="value"></param> /// <returns></returns> public static bool HasRight<T>(this Enum type, T value) { try { return (((int)(object)type & (int)(object)value) == (int)(object)value); } catch { return false; } } /// <summary> /// 是否T完全相等 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type"></param> /// <param name="value"></param> /// <returns></returns> public static bool IsEquals<T>(this Enum type, T value) { try { return (int)(object)type == (int)(object)value; } catch { return false; } } /// <summary> /// 添加 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type"></param> /// <param name="value"></param> /// <returns></returns> public static T AddRight<T>(this Enum type, T value) { try { return (T)(object)(((int)(object)type | (int)(object)value)); } catch (Exception ex) { throw ex; } } /// <summary> /// 移除 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type"></param> /// <param name="value"></param> /// <returns></returns> public static T RemoveRight<T>(this Enum type, T value) { try { return (T)(object)(((int)(object)type & ~(int)(object)value)); } catch (Exception ex) { throw ex; } } } }