探讨⼀下C#⾥⾯的枚举与位或运算符
今天看《Pro Net 2.0 Windows Forms And Custom Cortrols In C#》时看到枚举⼀节,发现了在⼀个枚举⾥⾯需要合并多个值,看到了⽤到了”|”运算符,原来没怎么注意,今天想了⼀下为什么⽤”|”呢?
在MSDN⾥⾯看到了这样⼀句话:“⽤2的幂(即 1、2、4、8 等)定义枚举常量。这意味着组合的枚举常量中的各个标志都不重叠。”
于是写了⼀个例⼦:
[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
};
//测试
enum怎么用
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…..这样的只才会叠加,枚举会⾃动判断当前值,如果枚举⾥⾯有这个值当然就显⽰这个值了;如果没有就做匹配⽤加法看看那⼏个数加起来刚好是这个枚举值,但如果有⼏个数字加起来都等于这个值怎么办呢?还没遇到呢,⽬前这是我的理解,希望⼤⽜些指教!