位运算

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

//与
1010 & 1111 = 1010
//或
1010 | 1111 = 1111
//非
~1010 = 0101

位运算权限设计

首先创建一个权限枚举

[Flags]表示该枚举可以支持C#位运算

枚举的每一项值, 我们用2的n次方来赋值, 这样表示成二进制时刚好是1 = 0001, 2 = 0010, 4 = 0100, 8 = 1000等

每一位表示一种权限, 1表示有权限, 0表示没有

[Flags]
public enum Authority
{
	None = 0,
	Add = 1,
	Delete = 2,
	Update = 4,
	Query = 8
}

位运算权限操作


class Program
{
	static Authority CurrentAuth = Authority.None;
	static void Main(string[] args)
	{
		//0000 | 0001 = 0001
		CurrentAuth = AddAuth(Authority.Add);
		Console.WriteLine(CurrentAuth);

		//0001 | 0100 = 0101
		CurrentAuth = AddAuth(Authority.Update);
		Console.WriteLine(CurrentAuth);

		//0101 & 0001 = 0001
		Console.WriteLine(CheckAuth(Authority.Add));

		//0101 & ~0001 = 0101 & 1110 = 0100
		CurrentAuth = RemoveAuth(Authority.Add);
		Console.WriteLine(CurrentAuth);

		//0100 & 0001 = 0000
		Console.WriteLine(CheckAuth(Authority.Add));
		Console.ReadKey();
	}
	/// <summary>
	/// 添加权限
	/// </summary>
	/// <param name="auth"></param>
	/// <returns></returns>
	static Authority AddAuth(Authority auth)
	{
		return CurrentAuth | auth;
	}
	/// <summary>
	/// 移除权限
	/// </summary>
	/// <param name="auth"></param>
	/// <returns></returns>
	static Authority RemoveAuth(Authority auth)
	{
		return CurrentAuth & ~auth;
	}
	/// <summary>
	/// 检查权限
	/// </summary>
	/// <param name="auth"></param>
	/// <returns></returns>
	static bool CheckAuth(Authority auth)
	{
		return (CurrentAuth & auth) == auth ? true : false;
	}
}

运行结果:


Add
Add, Update
True
Update
False


权限的添加, 使用与运算来实现,如:0000 | 0001 = 0001

权限的移除, 使用与运算+非运算来实现,如:0101 & ~0001 = 0101 & 1110 = 0100

检查权限, 使用与运算,如:0001 | 0100 = 0101

C# 权限 最后修改于 2015-06-29 16:28:49
上一篇