1.首先定义一个枚举:
enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 };
2.判断所给的值在枚举中是否存在
string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
foreach (string colorString in colorStrings)
{
Colors colorValue;
//将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象
if (Enum.TryParse(colorString, true, out colorValue))、
{
if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
else
Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
}
else
{
Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);
}
}