C#枚举中使用Flags特性

  • 2019 年 10 月 7 日
  • 筆記

这种用处很大,比如权限、执行状态等,都可以用一个int型保存到数据库中,C#中使用枚举可以处理这个问题。

    [Flags]      public enum Permission      {          create = 1,          read = 2,          update = 4,          delete = 8,      }

C#对该类型的操作如下:

            Permission permission = Permission.create | Permission.read | Permission.update | Permission.delete;              Console.WriteLine("1、枚举创建,并赋值……");              Console.WriteLine(permission.ToString());              Console.WriteLine((int)permission);                permission = (Permission)Enum.Parse(typeof(Permission), "5");              Console.WriteLine("2、通过数字字符串转换……");              Console.WriteLine(permission.ToString());              Console.WriteLine((int)permission);                permission = (Permission)Enum.Parse(typeof(Permission), "update, delete, read", true);              Console.WriteLine("3、通过枚举名称字符串转换……");              Console.WriteLine(permission.ToString());              Console.WriteLine((int)permission);                permission = (Permission)7;              Console.WriteLine("4、直接用数字强制转换……");              Console.WriteLine(permission.ToString());              Console.WriteLine((int)permission);                permission = permission & ~Permission.read;              Console.WriteLine("5、去掉一个枚举项……");              Console.WriteLine(permission.ToString());              Console.WriteLine((int)permission);                permission = permission|Permission.delete;              Console.WriteLine("6、加上一个枚举项……");              Console.WriteLine(permission.ToString());              Console.WriteLine((int)permission);

在数据库中判断:

AND (@permission IS NULL OR @permission=0 OR permission &@permission =@permission)

上面的sql语句同样可以判断多个权限