enum以及位域运算符的高级用法(详解-最易理解位域运算的教程)

位域支持的运算符

1. “|”:表示两边求并集(元素相加,相同元素只出现一次)

Week week = Week.Tuesday | Week.Monday | Week.Monday;  MessageBox.Show(Convert.ToString(week));     这段代码的结果就是 Monday,Tuesday

2. “&”:表示两边是否其中一个是另外一个的子集,如果是返回子集,否则返回0(如果其中一个包含另外一个,返回被包含的,否则返回0)

week = Week.Monday & week;  MessageBox.Show(week.ToString());与week = week & Week.Monday;  MessageBox.Show(week.ToString());     上面这两段代码的结果是相同的,如果week的初始值为:Monday,Tuesday,返回的结果为:Monday

3.“^”:表示从两者的并集中去除两者的交集(把两个的元素合并到一起,如果两个中有公共元素,要将这个公共元素从合并的结果中去除)

week = (Week.Monday | Week.Wednesday)^ (Week.Tuesday | Week.Monday);  MessageBox.Show(week.ToString());  week = (Week.Monday | Week.Wednesday) ^ (Week.Tuesday | Week.Sunday);  MessageBox.Show(week.ToString());     上面两个返回的结果应该为:Tuesday,Wednesday 和 Monday,Tuesday,Wednesday,Sunday

4.“~”:表示取反,返回的结果我还不知道应该是什么,以后再查一下。用法主要和“&”一起使用,例如:去除其中的某个元素

week = Week.Tuesday | Week.Monday | Week.Wednesday;  week = week &(~Week.Monday);  MessageBox.Show(week.ToString());     上面返回的结果为:Tuesday,Wednesday

你可能感兴趣的:(enum,java,位运算)