C# 列舉 TryParse() 方法


TryParse() 方法將一個或多個列舉常量的字串表示形式轉換為等效的列舉物件。

首先,設定一個列舉。

enum Vehicle { Bus = 2, Truck = 4, Car = 10 };

現在,讓我們宣告一個字串陣列並設定一些值。

string[] VehicleList = { "2", "3", "4", "bus", "Truck", "CAR" };

現在,使用 Enum TryParse() 方法對值進行相應地解析。

示例

線上示例演示

using System;
public class Demo {
   enum Vehicle { Bus = 2, Truck = 4, Car = 10 };
   public static void Main() {
      string[] VehicleList = { "2", "3", "4", "bus", "Truck", "CAR" };
      foreach (string val in VehicleList) {
         Vehicle vehicle;
         if (Enum.TryParse(val, true, out vehicle))
         if (Enum.IsDefined(typeof(Vehicle), vehicle) | vehicle.ToString().Contains(","))
         Console.WriteLine("Converted '{0}' to {1}", val, vehicle.ToString());
         else
         Console.WriteLine("{0} is not a value of the enum", val);
         else
         Console.WriteLine("{0} is not a member of the enum", val);
      }
   }
}

輸出

Converted '2' to Bus
3 is not a value of the enum
Converted '4' to Truck
Converted 'bus' to Bus
Converted 'Truck' to Truck
Converted 'CAR' to Car

更新於: 2020 年 6 月 23 日

9K+ 瀏覽

開啟你的職業生涯

完成課程獲得認證

入門
廣告
© . All rights reserved.