结合枚举类型和异或操作实现开关 --使代码更清晰
2007-09-11 22:27
295 查看
可以使用一个整数代表32个独立的布尔标记,综合用枚举类型和位的异或操作可以方便的设置每个布尔标记,用来作为开关。每个枚举值代表一个开关true or false。
标记开关主要用在权限系统中,用来表现一个用户具有何种权限。
示例如下:
public enum Bitwise : int
{
Setting1 = 1, //0000 0001
Setting2 = 2, //0000 0010
Setting3 = 4, //0000 0100
Setting4 = 8, //0000 1000
Setting5 = 16, //0001 0000
Setting6 = 32, //0010 0000
Setting7 = 64, //0100 0000
Setting8 = 128, //1000 0000
};
该结构体具有设置获取指定Bitwise值的方法
public struct IntAsBits
{
int settings;
public IntAsBits(Bitwise settings)
{
this.settings = (int)settings;
}
public bool this[int index]
{
get
{ //check the bit at index and return true or false
return (settings & (1 << index)) != 0;
}
set
{
if (value)
settings |= (1 << index); //turns the bit at index on
else
settings &= ~(1 << index); //turns the bit at index off
}
}
}
具体使用 可以方便的获取和设置指定二进制的值
Bitwise settings = Bitwise.Setting2 | Bitwise.Setting4 | Bitwise.Setting8;
IntAsBits bits = new IntAsBits(settings);
for(int i=0;i<8;i++)
{
Console.WriteLine(bits[i]);
}
优点:效率高 直观 便捷
摘自:http://dotnetslackers.com/articles/net/Bitwise_Operations_with_Enumerations.aspx
Created by jecray
标记开关主要用在权限系统中,用来表现一个用户具有何种权限。
示例如下:
public enum Bitwise : int
{
Setting1 = 1, //0000 0001
Setting2 = 2, //0000 0010
Setting3 = 4, //0000 0100
Setting4 = 8, //0000 1000
Setting5 = 16, //0001 0000
Setting6 = 32, //0010 0000
Setting7 = 64, //0100 0000
Setting8 = 128, //1000 0000
};
该结构体具有设置获取指定Bitwise值的方法
public struct IntAsBits
{
int settings;
public IntAsBits(Bitwise settings)
{
this.settings = (int)settings;
}
public bool this[int index]
{
get
{ //check the bit at index and return true or false
return (settings & (1 << index)) != 0;
}
set
{
if (value)
settings |= (1 << index); //turns the bit at index on
else
settings &= ~(1 << index); //turns the bit at index off
}
}
}
具体使用 可以方便的获取和设置指定二进制的值
Bitwise settings = Bitwise.Setting2 | Bitwise.Setting4 | Bitwise.Setting8;
IntAsBits bits = new IntAsBits(settings);
for(int i=0;i<8;i++)
{
Console.WriteLine(bits[i]);
}
优点:效率高 直观 便捷
摘自:http://dotnetslackers.com/articles/net/Bitwise_Operations_with_Enumerations.aspx
Created by jecray
相关文章推荐
- python3结合openpyxl库实现excel操作的实例代码
- C# 注册表 操作实现代码
- C语言 枚举类型在VS2010上无法实现自增,自减操作
- Python 文件操作实现代码
- 解析php DOMElement 操作xml 文档的实现代码
- android 代码实现模拟用户点击、滑动等操作
- js模拟权限选择实现代码(select操作)
- PowerShell连接SQL SERVER数据库进行操作的实现代码
- 实现声音开关的代码
- C#使用互斥量(Mutex)实现多进程并发操作时多进程间线程同步操作(进程同步)的简单示例代码及使用方法
- jenkins结合脚本实现代码自动化部署及一键回滚至上一版本
- jQuery 操作option的实现代码
- 用C#实现操作XML文件的公共类代码
- 用两个栈实现队列的操作代码
- 各式各样的导航条效果css3结合jquery代码实现
- 用异或操作,实现简单的密码加解密处理
- java计算器实现,百行代码,清晰注释
- php下拉选项的批量操作的实现代码
- Python 字符串操作实现代码(截取/替换/查找/分割)