惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

W
WeLiveSecurity
T
The Exploit Database - CXSecurity.com
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Security @ Cisco Blogs
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
腾讯CDC
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
The Blog of Author Tim Ferriss
Microsoft Azure Blog
Microsoft Azure Blog
罗磊的独立博客
F
Full Disclosure
博客园 - 【当耐特】
C
CERT Recently Published Vulnerability Notes
Engineering at Meta
Engineering at Meta
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Threatpost
I
Intezer
V2EX - 技术
V2EX - 技术
H
Hackread – Cybersecurity News, Data Breaches, AI and More
The Hacker News
The Hacker News
小众软件
小众软件
Google DeepMind News
Google DeepMind News
T
Tailwind CSS Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
B
Blog RSS Feed
Microsoft Security Blog
Microsoft Security Blog
N
News | PayPal Newsroom
MyScale Blog
MyScale Blog
AI
AI
Vercel News
Vercel News
Spread Privacy
Spread Privacy
美团技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The GitHub Blog
The GitHub Blog
V
Vulnerabilities – Threatpost
Schneier on Security
Schneier on Security
Cyberwarzone
Cyberwarzone
G
GRAHAM CLULEY
Help Net Security
Help Net Security
Hacker News: Ask HN
Hacker News: Ask HN
Google DeepMind News
Google DeepMind News
MongoDB | Blog
MongoDB | Blog
L
LINUX DO - 热门话题
U
Unit 42
L
LangChain Blog
Recent Announcements
Recent Announcements

博客园 - xiaosonl

学习手札#3 NHibernate缓存 产品的简单性 关于过度设计的思考(上) 让ASP.NET MVC的Controller输出不同类型数据 学习手札#2 故事点和小时数的思考 学习笔记#1 键值对数据库 SQLite数据迁移 探讨一种在Silverlight不普及情况下的部署策略 有用的文档 Silverlight产品布署策略 探讨一种Silverlight的异步编程模式 代码的注释 下半年要看完消化的技术类书籍 中小型企业的人员流失 谈谈Ruby On Rails和ASP.NET 工作中的系统学习 Uml中的关联与依赖关系 TDD与重构设计 Silverlight中JavaSciprt无法访问托管类抽象成员的解决方法
C#中使用位运算来实现权限管理
xiaosonl · 2009-06-17 · via 博客园 - xiaosonl

2009-06-17 20:46  xiaosonl  阅读(2283)  评论()    收藏  举报

常用的位运算主要有与(&), 或(|)和非(~), 比如:

1 & 0 = 0, 1 | 0 = 1, ~1 = 0

在设计权限时, 我们可以把权限操作转换为位运算来处理.

第一步, 先建立一个枚举表示所有的权限操作:

[Flags]
public enum Permissions
{ 
    Insert = 1,
    Delete = 2,
    Update = 4,
    Query = 8
}
 

[Flags]表示该枚举可以支持位运算, 而枚举的每一项值, 我们用2的n次方来赋值, 这样表示成二进制时刚好是1 = 0001, 2 = 0010, 4 = 0100, 8 = 1000等, 每一位表示一种权限, 1表示有该权限, 0表示没有.

接下来是权限的运算:

1. 权限的加法, 使用与运算来实现. 我们知道, 0001 | 0100 = 0101, 这样就表示同时具有第一位和第三位的权限了, 枚举表示为:

Permissions per = Permissions.Insert | Permissions.Update

2. 权限的减法, 使用与运算+非运算来实现, 如上面要去掉Insert权限, 操作为:

Permissions per &= ~Permissions.Insert

即是 0101 & ~0001 = 0101 & 1110 = 0100

3. 权限的判断, 使用与运算, 当判断用一用户是否具有该操作权限时, 要把用户的的权限与操作权限进行与运算, 如果得到的结果仍是操作权限, 则表示用户具有该权限:

Permissions per = Permissions.Insert | Permissions.Update;
if(per & Permissions.Insert = Permissions.Insert) 
{
    //有操作权限
}
比较过程为 0101 & 0001 = 0001, 0001的0位用与运算把其它位都置成0, 变成只比较1的这一位.