位枚举

使用位类型枚举,可以组合枚举值,如果需要多个枚举值,可以用位枚举

 

枚举添加[Flags],标识位枚举

 

案例:

    [Flags]
    enum Styles
    {
        white=1,
        yellow=2,
        grean=4,
        blue=8,
        gray=16,
        orange=32,
        pink=64,
        red=128,
        black=256
    }

//上面枚举定义需要小小计算一下,如果想偷懒可以用下面的方式
[Flags]
public enum Roles
{
Admin = 1 << 0,
Member = 1 << 1,
Manager = 1 << 2,
Operator = 1 << 3
}

var style = Styles.white | Styles.yellow | Styles.grean;//组合枚举
            Console.WriteLine(style.ToString());//white,yellow,grean
            Console.WriteLine(((Styles)7).ToString());//white,yellow,grean
            Console.WriteLine((style & Styles.white) != 0?"true":"false");//是否包含指定枚举,true
            //从组合中删除元素,第一种
            if ((style & Styles.white) != 0)
            {
                Console.WriteLine(style ^ Styles.white);//yellow,grean
            }
            //从组合中删除元素,第二种
            Console.WriteLine(style & (~Styles.white));

 

参考:https://www.cnblogs.com/willick/p/csharp-enum-superior-tactics.html

posted @ 2020-05-11 14:01  .Neterr  阅读(206)  评论(0编辑  收藏  举报