枚举类型或运算

1.使用枚举类型进行按位或运算,应该用2的幂(一、二、四、8等) 来定义枚举常量,以确保组按位运算结果与枚举中的各个标志都不重叠;ide

2.当可能须要对枚举类型进行按位运算时,应该对枚举使用FlagsAttribute /Flags属性,这样当对枚举使用按位运算时才能够解析出各个具体的枚举常量名,而不单单是组合值;
spa

3. None 用做值为零的标志枚举常量的名称;3d

4.若是明显存在应用程序须要表示的默认状况,考虑使用值为零的枚举常量表示默认值。code

示例代码1,不加FlagsAttribute:blog

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             OprationType opration = OprationType.Read | OprationType.Write;
 6 
 7             Console.WriteLine(opration.ToString());
 8             Console.Read();
 9         }
10     }
11 
12     //[FlagsAttribute]
13     public enum OprationType
14     {
15         None = 0,
16         Read=1,
17         Write=2,
18     }
View Code

运行结果:get

示例代码2,加入FlagsAttribute:string

 1  class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             OprationType opration = OprationType.Read | OprationType.Write;
 6 
 7             Console.WriteLine(opration.ToString());
 8             Console.Read();
 9         }
10     }
11 
12     [FlagsAttribute]
13     public enum OprationType
14     {
15         None = 0,
16         Read=1,
17         Write=2,
18     }
View Code

运行结果:it

5.枚举中的-=操做io

示例代码:event

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             OprationType opration = OprationType.Read | OprationType.Write;
 6             opration -= OprationType.Write;
 7             Console.WriteLine(opration.ToString());
 8             Console.Read();
 9         }
10     }
11 
12     [FlagsAttribute]
13     public enum OprationType
14     {
15         None = 0,
16         Read=1,
17         Write=2,
18     }
View Code

运行结果:

 

参考:http://msdn.microsoft.com/zh-cn/library/system.enum.aspx

相关文章
相关标签/搜索