C#枚举TryParse()方法
TryParse()方法将一个或多个枚举常量的字符串表示形式转换为等效的枚举对象。
首先,设置一个枚举。
enum Vehicle { Bus = 2, Truck = 4, Car = 10 };现在,让我们声明一个字符串数组并设置一些值。
string[] VehicleList = { "2", "3", "4", "bus", "Truck", "CAR" };现在使用EnumTryParse()方法相应地解析值。
示例
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
热门推荐
1 送蛇的祝福语简短
4 年月日祝福语简短
10 祝福语大全简短6个
11 新生祝福语简短8字
12 爱情祝福语大全 简短实际
13 团队文案祝福语简短励志
14 启程出发路途祝福语简短
15 工厂祝福语简短的句子
16 春节感恩祝福语简短的
17 微信晚上祝福语简短
18 妈妈给宝贝祝福语简短