--- tags: C#, Enum authors: Anderson --- ###### tags: `C#` `Enum` # 列舉項目處理 ## :memo: 說明 為了與DB中的值方便比對,可能會有下面的處理方式: 1. 將列舉的項目轉成字串值 ex: var testB = DomesticStatus.作廢.ToString(); 3. 將字串轉換成列舉的項目 ex: var testD = (DomesticStatus)Enum.Parse(typeof(DomesticStatus), "作廢"); ## :memo: Code ``` C# using System; namespace Test { class Program { public enum DomesticStatus { 新單, 已送出申請, 已核可, 申請處理中, 結案, 空趟, 作廢 } static void Main(string[] args) { var testA = DomesticStatus.作廢; var testB = DomesticStatus.作廢.ToString(); var testC = "作廢"; var testD = (DomesticStatus)Enum.Parse(typeof(DomesticStatus), "作廢"); Console.WriteLine($@"testA Value : {testA} Type : {testA.GetType().Name} "); Console.WriteLine($@"testB Value : {testB} Type : {testB.GetType().Name} "); Console.WriteLine($@"testC Value : {testC} Type : {testC.GetType().Name} "); if (testB == testC) { Console.WriteLine(@"if (testB == testC) =>true "); } Console.WriteLine($@"testD Value : {testD} Type : {testD.GetType().Name} "); // 字串轉成列舉值 if(testD == DomesticStatus.作廢) { Console.WriteLine(@"if(testD == DomesticStatus.作廢) =>true"); } Console.ReadKey(); } } } ``` ## :memo: 執行結果 ![](https://i.imgur.com/6GKgEuY.png)