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);
}
}