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());
}
}