TryParse() विधि एक या अधिक गणना स्थिरांक के स्ट्रिंग प्रतिनिधित्व को समकक्ष गणना वस्तु में परिवर्तित करती है।
उदाहरण
सबसे पहले एक 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