现在的位置: 首页 > 综合 > 正文

探讨一下C#里面的枚举与位或运算符

2013年06月16日 ⁄ 综合 ⁄ 共 1912字 ⁄ 字号 评论关闭
  今天看《Pro Net 2.0 Windows Forms And Custom Cortrols In C#》时看到枚举一节,发现了在一个枚举里面需要合并多个值,看到了用到了”|”运算符,原来没怎么注意,今天想了一下为什么用”|”呢?
  MSDN里面看到了这样一句话:“用2的幂(即 1248 等)定义枚举常量。这意味着组合的枚举常量中的各个标志都不重叠。”
  于是写了一个例子:

        [FlagsAttribute]
        
enum Colors_1
        
{
            Red 
= 1, Green = 2, Blue = 4, Yellow = 8
        }
;
        
//测试
        private void button1_Click(object sender, EventArgs e)
        
{
            Colors_1 color_1 
= Colors_1.Red | Colors_1.Green | Colors_1.Blue 
| Colors_1.Yellow;

            
string strResult = color_1.ToString() + " " + ((int)color_1)
.ToString();
            MessageBox.Show(strResult);
        }

输出结果:

咦!  1 + 2 + 4 + 8 = 15 刚刚等于15,难道这是巧合?
全部显示出来了,安逸!

再写个例子试试:

        [FlagsAttribute]
        
enum Colors_2
        
{
            Red 
= 1, Green = 2, Blue = 3, Yellow = 4
        }
;
        
//测试
        private void button1_Click(object sender, EventArgs e)
        
{
            Colors_2 color_2 
= Colors_2.Red | Colors_2.Green | Colors_2.Blue
 
| Colors_2.Yellow;

            
string strResult = color_2.ToString() + " " + ((int)color_2).ToString();
            MessageBox.Show(strResult);
        }

输出结果:

晕,怎么没把颜色全部显示出来呀?
咦!3 + 4 = 7 刚好显示枚举值为3,4的两种颜色

再写一个例子呢?

        //测试
        private void button1_Click(object sender, EventArgs e)
        
{
            Colors_1 c 
= (Colors_1)Enum.Parse(typeof(Colors_1), "7");
            MessageBox.Show(c.ToString() 
+ " " + ((int)c).ToString());
        }

输出结果:

居然会自动转换成相应的枚举值,厉害!

 再来我加个枚举为7的值:

        [FlagsAttribute]
        
enum Colors_1
        
{
            Red 
= 1, Green = 2, Blue = 4, Yellow = 8, Seven = 7
        }
;
        
//测试
        private void button1_Click(object sender, EventArgs e)
        
{
            Colors_1 c 
= (Colors_1)Enum.Parse(typeof(Colors_1), "7");
            MessageBox.Show(c.ToString() 
+ " " + ((int)c).ToString());
        }

输出结果:

印证了MSDN那句话,只有将枚举值设置为0,2,4,8…..这样的只才会叠加,枚举会自动判断当前值,如果枚举里面有这个值当然就显示这个值了;如果没有就做匹配用加法看看那几个数加起来刚好是这个枚举值,但如果有几个数字加起来都等于这个值怎么办呢?还没遇到呢,目前这是我的理解,希望大牛些指教!

抱歉!评论已关闭.