如果对一个值可以包含多个,那么可以使用枚举,加上Flags
本文告诉大家如何写一个 Flags。
在写前,需要知道一些基础知识,取反、或、与,如果不知道的话,请去看看基础。
当然,这些太复杂了,我也不会在这里解释。
假如有类型
1 2 3 4 5 6 7 8 |
[Flags] <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> Show { A = <span class="hljs-number">0x00000001</span>, B = <span class="hljs-number">0x00000010</span>, C = <span class="hljs-number">0x00000100</span>, D = <span class="hljs-number">0x00001000</span>, } |
合并多个,使用 |
1 |
<span class="hljs-operator"><span class="hljs-keyword">Show</span> <span class="hljs-keyword">show</span>=<span class="hljs-keyword">Show</span>.A | <span class="hljs-keyword">Show</span>.B</span> |
一个简单方法是用 HasFlag,但是一个方法是用 &
1 2 3 4 |
<span class="hljs-operator"><span class="hljs-keyword">Show</span> <span class="hljs-keyword">show</span>=<span class="hljs-keyword">Show</span>.A | <span class="hljs-keyword">Show</span>.B;</span> <span class="hljs-operator"><span class="hljs-keyword">show</span>.HasFlag(<span class="hljs-keyword">Show</span>.A);</span> //其他 bool 包含=(<span class="hljs-operator"><span class="hljs-keyword">show</span> & <span class="hljs-keyword">Show</span>.A)!=<span class="hljs-number">0</span>;</span> |
1 2 |
<span class="hljs-operator"><span class="hljs-keyword">Show</span> <span class="hljs-keyword">show</span>=<span class="hljs-keyword">Show</span>.A | <span class="hljs-keyword">Show</span>.B;</span> <span class="hljs-operator"><span class="hljs-keyword">show</span>=<span class="hljs-keyword">show</span> & (~<span class="hljs-keyword">Show</span>.A);</span> |
1 2 3 4 5 6 7 8 9 10 |
<span class="hljs-operator"><span class="hljs-keyword">Show</span> <span class="hljs-keyword">show</span>=<span class="hljs-keyword">Show</span>.A | <span class="hljs-keyword">Show</span>.B;</span> bool 包含=(<span class="hljs-operator"><span class="hljs-keyword">show</span> & <span class="hljs-keyword">Show</span>.A)!=<span class="hljs-number">0</span>;</span> if(包含) { <span class="hljs-operator"><span class="hljs-keyword">show</span>=<span class="hljs-keyword">show</span> & (~<span class="hljs-keyword">Show</span>.A);</span> } else { <span class="hljs-operator"><span class="hljs-keyword">show</span>=<span class="hljs-keyword">show</span> | <span class="hljs-keyword">Show</span>.A;</span> } |