【C#】【温故知新】枚举类型Enum定义位标志,与或非的计算

使用枚举类型定义位标志,从而使该枚举类型的实例可以存储枚举数列表中定义的值的任意组合。每个枚举值值都是2的n次幂,指数依次递增。

官方文档:

枚举类型(C# 编程指南),FlagsAttribute Class

示例:

//组合枚举常量中的各个标志不会重叠,0表示未设置任何标志
// 0 - None
// 1 - Black
// 2 - Red
// 3 - Black, Red
// 4 - Green
// 5 - Black, Green
// 6 - Red, Green
// 7 - Black, Red, Green
// 8 - Blue
// 9 - Black, Blue
//10 - Red, Blue
//11 - Black, Red, Blue
//12 - Green, Blue
//13 - Black, Green, Blue
//14 - Red, Green, Blue
//15 - Black, Red, Green, Blue
public enum ColorGroup
{
    None = 0,
    Black = 1,
    Red = 2,
    Green = 4,
    Blue = 8
}

public class NewBehaviourScript : MonoBehaviour
{
    void Start()
    {
        //或运算,并集
        ColorGroup colorGroup1 = ColorGroup.Black | ColorGroup.Blue;
        Debug.Log(colorGroup1);     //9 (Black, Blue)

        ColorGroup colorGroup2 = colorGroup1 | ColorGroup.Red;
        Debug.Log(colorGroup2);     //11 (Black, Blue, Red)

        //与运算,交集
        ColorGroup colorGroup3 = colorGroup1 & ColorGroup.Blue;
        Debug.Log(colorGroup3);     //Blue

        //非运算,移除指定值
        ColorGroup colorGroup4 = colorGroup1^ ColorGroup.Blue;
        Debug.Log(colorGroup4);     //Black

    }
}

 

你可能感兴趣的:(C#)