一种简单的直观的高效的权限设计
2010-09-30 22:41:33 来源:WEB开发网 闂傚倸鍊搁崐鎼佸磹閹间礁纾归柟闂寸绾惧綊鏌熼梻瀵割槮缁炬儳缍婇弻鐔兼⒒鐎靛壊妲紒鎯у⒔閹虫捇鈥旈崘顏佸亾閿濆簼绨绘い鎺嬪灪閵囧嫰骞囬姣挎捇鏌熸笟鍨妞ゎ偅绮撳畷鍗炍旈埀顒勭嵁婵犲嫮纾介柛灞捐壘閳ь剛鎳撻~婵嬪Ω閳轰胶鐤呯紓浣割儐椤戞瑩宕ョ€n喗鐓曟い鎰靛亝缁舵氨绱撻崘鈺傜婵﹤顭峰畷鎺戔枎閹搭厽袦婵犵數濮崑鎾绘⒑椤掆偓缁夌敻骞嗛悙鍝勭婵烇綆鍓欐俊鑲╃磼閹邦収娈滈柡灞糕偓鎰佸悑閹肩补鈧尙鏁栧┑鐐村灦閹稿摜绮旈悽绋课﹂柛鏇ㄥ灠閸愨偓濡炪倖鍔﹀鈧繛宀婁邯濮婅櫣绱掑Ο璇茶敿闂佺ǹ娴烽弫璇差嚕婵犳碍鏅插璺猴工瀹撳棝姊虹紒妯哄缂佷焦鎸冲畷鎴﹀箻鐠囧弶宓嶅銈嗘尰缁嬫垶绂嶉悙顒佸弿婵☆垳鍘ф禍楣冩倵濮樼偓瀚�

我们先试用一下,你就能感觉到神奇之处:
1 //创建一个用户
2 User admin = new User();
3 admin.Permissions = PermissionTypes.Read
4 | PermissionTypes.Write
5 | PermissionTypes.Delete;
6
7 //验证权限
8 bool canRead = ((PermissionTypes.Read & admin.Permissions) == PermissionTypes.Read);
9 bool canWrite = ((PermissionTypes.Write & admin.Permissions) == PermissionTypes.Write);
10 bool canCreate = ((PermissionTypes.Create & admin.Permissions) == PermissionTypes.Create);
11
12 //查看结果
13 Console.WriteLine(canRead); //true
14 Console.WriteLine(canWrite); //true
15 Console.WriteLine(canCreate); //false
16
利用了'|'和'&'两个操作。但是这样看起来很是很别捏,初始化权限和验证权限用了一长串'|'和'&'运算的代码。很不直观。我在System.Enum中扩展一些方法供你调用,代码如下。
1 //是否存在权限
2 public static bool Has<T>(this System.Enum type, T value)
3 {
4 try
5 {
6 return (((int)(object)type & (int)(object)value) == (int)(object)value);
7 }
8 catch
9 {
10 return false;
11 }
12 }
13 //判断权限
14 public static bool Is<T>(this System.Enum type, T value)
15 {
16 try
17 {
18 return (int)(object)type == (int)(object)value;
19 }
20 catch
21 {
22 return false;
23 }
24 }
25 //添加权限
26 public static T Add<T>(this System.Enum type, T value)
27 {
28 try
29 {
30 return (T)(object)(((int)(object)type | (int)(object)value));
31 }
32 catch (Exception ex)
33 {
34 throw new ArgumentException(
35 string.Format(
36 "不能添加类型 '{0}'",
37 typeof(T).Name
38 ), ex);
39 }
40 }
41
42 //移除权限
43 public static T Remove<T>(this System.Enum type, T value)
44 {
45 try
46 {
47 return (T)(object)(((int)(object)type & ~(int)(object)value));
48 }
49 catch (Exception ex)
50 {
51 throw new ArgumentException(
52 string.Format(
53 "不能移除类型 '{0}'",
54 typeof(T).Name
55 ), ex);
56 }
57 }
更多精彩
赞助商链接