首页 > 代码库 > c# 权限二进制操作

c# 权限二进制操作

技术分享
   /// <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    }
View Code
技术分享
    class Program    {        static void Main(string[] args)        {            //初始化一个新增权限            var demo = InsertPermission(PermissionEnum.Insert);            Console.WriteLine(demo);            //再增加一个查询权限            demo = InsertPermission(PermissionEnum.Query, demo);            Console.WriteLine(demo);            //再增加一个删除权限            demo = InsertPermission(PermissionEnum.Delete, demo);            Console.WriteLine(demo);            //删除一个新增权限            demo = DeletePermission(PermissionEnum.Insert, demo);            Console.WriteLine(demo);            //判断是否拥有新增权限            Console.WriteLine(GetPermission(PermissionEnum.Insert, demo));            //判断是否拥有查询权限            Console.WriteLine(GetPermission(PermissionEnum.Query, demo));            Console.Read();        }        /// <summary>        /// 增加权限        /// </summary>        /// <param name="perType">需要增加什么权限(增删改查)</param>        /// <param name="userPer">用户原来的权限</param>        /// <returns></returns>        public static int InsertPermission(PermissionEnum perType, int userPer = (int)PermissionEnum.Init)        {            //或运算  真假 为真;            return userPer | (int)perType;        }        /// <summary>        /// 删除权限        /// </summary>        /// <param name="perType">需要删除什么权限(增删改查)</param>        /// <param name="userPer">用户原来的权限</param>        /// <returns></returns>        public static int DeletePermission(PermissionEnum perType, int userPer = (int)PermissionEnum.Init)        {            //~补位,~000010 = 111101            //&与,真真为真,真假为假            return userPer & ~(int)perType;        }        /// <summary>        /// 判断是否拥有权限        /// </summary>        /// <param name="perType">判断是否拥有的权限类型</param>        /// <param name="userPer">用户原来的权限</param>        /// <returns></returns>        public static bool GetPermission(PermissionEnum perType, int userPer = (int)PermissionEnum.Init)        {            //&与,真真为真,真假为假            //判断出来的数不等于零,那就是拥有该权限            return (userPer & (int)perType) != 0;        }
View Code

 

c# 权限二进制操作