Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด Enum.TryParse() ใน C#

เมธอด TryParse() แปลงการแสดงผลสตริงของค่าคงที่แบบ Enum หนึ่งหรือหลายค่า ให้กลายเป็นอ็อบเจกต์ Enum ที่เทียบเท่า

ขั้นแรก ให้กำหนด Enum:

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