Enum Flags 예제

using System; [Flags] public enum BitFlag { None = 0, Bit1 = 1 << 0, Bit2 = 1 << 1, Bit3 = 1 << 2, Bit4 = 1 << 3, Bit5 = 1 << 4, Bit6 = 1 << 5, Bit7 = 1 << 6, Bit8 = 1 << 7, Bit9 = 1 << 8, Bit10 = 1 << 9, Bit11 = 1 << 11, Bit12 = 1 << 12, Bit13 = 1 << 13, Bit14 = 1 << 14, Bit15 = 1 << 15, Bit16 = 1 << 16, Bit17 = 1 << 17, Bit18 = 1 << 18, Bit19 = 1 << 19, Bit20 = 1 << 20, Bit21 = 1 << 21, Bit22 = 1 << 22, Bit23 = 1 << 23, Bit24 = 1 << 24, Bit25 = 1 << 25, Bit26 = 1 << 26, Bit27 = 1 << 26, Bit28 = 1 << 27, Bit29 = 1 << 28, Bit30 = 1 << 29, Bit31 = 1 << 30, Bit32 = 1 << 31, } class Program { static void Main(string[] args) { BitFlag testFlag = BitFlag.None; testFlag.Print("Add", BitFlag.Bit4); testFlag.Print("Remove", BitFlag.Bit4); testFlag.Print("Reversal", BitFlag.Bit4); testFlag.Print("Has", BitFlag.Bit4); testFlag.Print("Add", BitFlag.Bit4 | BitFlag.Bit8); testFlag.Print("Remove", BitFlag.Bit4); testFlag.Print("Reversal", BitFlag.Bit8); testFlag.Print("Has", BitFlag.Bit4 | BitFlag.Bit8); } } public static class BitMask { public static bool HasFlag(BitFlag mask, BitFlag checkFlag) { return (mask & checkFlag) != 0; } public static void AddFlag(this ref BitFlag mask, BitFlag flag) { mask |= flag; } public static void RemoveFlag(this ref BitFlag mask, BitFlag flag) { mask &= ~flag; } public static void ReversalFlag(this ref BitFlag mask, BitFlag flag) { mask ^= flag; } public static void Print(this ref BitFlag print, string action, BitFlag bitFlag) { Console.WriteLine($"시작 : Flag = {print}, Bit = {Convert.ToString((int)print, 2)}"); switch (action) { case "Has": var maskBitStr = Convert.ToString((int)print, 2); var checkFlagBitStr = Convert.ToString((int)bitFlag, 2); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine($"비교 : mask({print}, {maskBitStr}) & checkFlag({bitFlag}, {checkFlagBitStr})"); Console.ResetColor(); Console.WriteLine($"결과 : {HasFlag(print, bitFlag)}"); break; case "Add": print.AddFlag(bitFlag); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"추가 : Flag |= {bitFlag}({Convert.ToString((int)bitFlag, 2)})"); Console.ResetColor(); Console.WriteLine($"결과 : Flag = {print}, Bit = {Convert.ToString((int)print, 2)}"); break; case "Remove": print.RemoveFlag(bitFlag); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"제거 : Flag &= ~{bitFlag}({Convert.ToString((int)~bitFlag, 2)})"); Console.ResetColor(); Console.WriteLine($"결과 : Flag = {print}, Bit = {Convert.ToString((int)print, 2)}"); break; case "Reversal": print.ReversalFlag(bitFlag); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"반전 : Flag ^= {bitFlag}({Convert.ToString((int)bitFlag, 2)})"); Console.ResetColor(); Console.WriteLine($"결과 : Flag = {print}, Bit = {Convert.ToString((int)print, 2)}"); break; } Console.WriteLine("-------------------------------------------"); } }


출력 결과



반응형