看到代码里有用位操作来判断条件的,以前没有这么用过,做个笔记:
int add = 2;int modify = 4;int delete = 8;Console.WriteLine((add | modify | delete) & add); //2Console.WriteLine((add | modify | delete) & modify); //4Console.WriteLine((add | modify | delete) & delete); //8
但是直接使用整数进行位操作,可读性不太好。
其实C#里有枚举,也可以实现,但是C#的枚举可读性应该更好
[Flags]enum OperatingAuthorization{ Add = 2, Modify = 4, Delete = 8}OperatingAuthorization allOperating = OperatingAuthorization.Add | OperatingAuthorization.Modify | OperatingAuthorization.Delete;Console.WriteLine(allOperating & OperatingAuthorization.Add); //Add
这个可以用于判断权限是否存在,
如allOperating & OperatingAuthorization.Add == OperatingAuthorization.Add,则可确定allOperating包含OperatingAuthorization.Add
这里可以假定allOperating是从数据库取出来的
新闻热点
疑难解答