C# FlagAttriute 的 小妙招

匿名 (未验证) 提交于 2019-12-02 23:49:02

FlagAttriute ,指示可将枚举视为位域(即一组标志)。

官网中文解说:https://docs.microsoft.com/zh-cn/dotnet/api/system.flagsattribute?redirectedfrom=MSDN&view=netframework-4.7.2

以下是对应的demo,可以利用该特性,将业务场景中的角色设定为:1,2,4,8 这种按位操作,再判断是否包含该角色~

 1  public class EnumDemo  2     {  3         public static void Test()  4         {   5             DirectionEnumType type = (DirectionEnumType)13;  6   7             //可以用来判断是否存在right值  8             bool IsExistRigth = ((type & DirectionEnumType.Right) == DirectionEnumType.Right);  9  10             Console.WriteLine(type); 11  12             Console.WriteLine(IsExistRigth); 13             Console.WriteLine(1 << 5); //2的5次方  32 14  15              //有对应值的会输出 int - string 数据,没有值的,则输出 int -int数据 16             for (int val = 0; val <= 16; val++) 17                 Console.WriteLine("{0,3} - {1:G}", val, (SingleHue)val); 18  19             Console.WriteLine("--------------------------------"); 20  21  22             //有值的,或者有对应的组合值的,会输出int -string数据,否则输出 int-int 数据 23             for (int val = 0; val <= 16; val++) 24                 Console.WriteLine("{0,3} - {1:G}", val, (MultiHue)val); 25  26             /* 27 Top, Bottom, Left 28 False 29 32 30   0 - None 31   1 - Black 32   2 - Red 33   3 - 3 34   4 - Green 35   5 - 5 36   6 - 6 37   7 - 7 38   8 - Blue 39   9 - 9 40  10 - 10 41  11 - 11 42  12 - 12 43  13 - 13 44  14 - 14 45  15 - 15 46  16 - 16 47  -------------------------------- 48   0 - None 49   1 - Black 50   2 - Red 51   3 - Black, Red 52   4 - Green 53   5 - Black, Green 54   6 - Red, Green 55   7 - Black, Red, Green 56   8 - Blue 57   9 - Black, Blue 58  10 - Red, Blue 59  11 - Black, Red, Blue 60  12 - Green, Blue 61  13 - Black, Green, Blue 62  14 - Red, Green, Blue 63  15 - Black, Red, Green, Blue 64  16 - 16 65              */ 66         }

 1    [Flags]  2     public enum DirectionEnumType  3     {  4         Top = 1,  5         Right = 2,  6         Bottom = 4,  7         Left = 8,  8     }  9  10     enum SingleHue : short 11     { 12         None = 0, 13         Black = 1, 14         Red = 2, 15         Green = 4, 16         Blue = 8 17     }; 18  19     // Define an Enum with FlagsAttribute. 20     [FlagsAttribute] 21     enum MultiHue : short 22     { 23         None = 0, 24         Black = 1, 25         Red = 2, 26         Green = 4, 27         Blue = 8 28     };

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!