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語句同樣可以判斷多個許可權