枚举的位运算

FlagsAttribute 类

FlagsAttribute属性就是枚举类型的一项可选属性。它的主要作用是可以将枚举作为位域处理,所谓位域是单个存储单元内相邻二进制位的集合。通过为枚举添加这个属性,可以改变枚举的一些行为来满足我们的需要,

1.只有要对数值执行按位运算(AND、OR、XOR)时才对枚举使用 FlagsAttribute 自定义属性。

2. 必须用 2 的幂(即 1、2、4、8 等)定义枚举常量。这意味着组合的枚举常量中的各个标志都不重叠。具体的位运算百度。

 

using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;

public class EnumTest : MonoBehaviour
{
    [FlagsAttribute]
    public enum ColorEnum
    {
        yellow = 1,
        blue = 2,
        white = 4,
        red = 8
    }
    // Use this for initialization
    void Start()
    {
        ColorEnum color_1 = ColorEnum.yellow | ColorEnum.blue | ColorEnum.white | ColorEnum.red;
                         //      0001|0010|0100|1000  =  1111   (15)
        Debug.Log(color_1.ToString() + ";" + ((int)color_1));

        ColorEnum color_2 = ColorEnum.yellow & ColorEnum.blue | ColorEnum.white | ColorEnum.red;
                         //      0001 &  0010 | 0100 | 1000   =   1100   (12)      ColorEnum.white | ColorEnum.red
        Debug.Log("ColorEnum.yellow & ColorEnum.blue | ColorEnum.white | ColorEnum.red:" + color_2.ToString() + ";" + ((int)color_2));

        ColorEnum color_3 = ColorEnum.yellow | ColorEnum.blue & ColorEnum.white & ColorEnum.red;
                       //        0001| 0010 & 0100 & 1000  = 0001| 0000= 0001  (1)  ColorEnum.yellow
        Debug.Log("ColorEnum.yellow | ColorEnum.blue & ColorEnum.white & ColorEnum.red:" + color_3.ToString() + ";" + ((int)color_3));


        Type colorType = typeof(ColorEnum);
        Debug.Log(Enum.GetName(colorType, 1));
        Array array = Enum.GetValues(colorType);
        foreach (var a in array)
        {
            Debug.Log(a.ToString() + ";" + (int)a);
        }
        ColorEnum c = (ColorEnum)Enum.Parse(colorType, "blue");
        Debug.Log(c.ToString());
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值