C#枚举中使用Flags特性
.NET中的枚举我们一般有两种用法,一是表示唯一的元素序列;还有就是用来表示多种复合的状态。这个时候一般需要为枚举加上[Flags]特性标记为位域,这样我们就可以用"或"运算符组合多个状态.
例如:
[Flags]
public enum Permission
{
create = 1,
read = 2,
update = 4,
delete = 8,
}
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)
引用:http://www.cnblogs.com/youring2/archive/2011/12/16/2289832.html