C#位操作与枚举的应用
看到代码里有用位操作来判断条件的,以前没有这么用过,做个笔记:
int add = 2;
int modify = 4;
int delete = 8;
Console.WriteLine((add | modify | delete) & add); //2
Console.WriteLine((add | modify | delete) & modify); //4
Console.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是从数据库取出来的
如果你觉得这篇文章对你有帮助或者使你有所启发,请点击右下角的推荐按钮,谢谢,:)