class Program
{
static void Main(string[] args)
{
string value = "12345";
Type enumType = typeof(Fruits);
Fruits fruit = Fruits.Apple;
try
{
fruit = (Fruits) Enum.Parse(enumType, value);
}
catch (ArgumentException)
{
Console.WriteLine(String.Format("{0} is no healthy food.", value));
}
Console.WriteLine(String.Format("You should eat at least one {0} per day.", fruit));
Console.ReadKey();
}
public enum Fruits
{
Apple,
Banana,
Orange
}
}
If you execute the code above the result shows:
You should eat at least one 12345 per day.
I really expected an ArgumentException to be thrown if a unknown name (string) is passed. Taking a close look at the Enum.Parse definition reveals:
Summary:
Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
Exceptions:
ArgumentException: enumType is not an Enum. -or- value is either an empty string or only contains white space. -or- value is a name, but not one of the named constants defined for the enumeration.
I.e. if a string representation of an integer is passed, a new enum value is created and now exception is thrown by design. Does this make sense?
At least I now know to call Enum.IsDefined(enumType, value)
prior to Enum.Parse()
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…