我将字符串类型的数值转换为相应的Enum。当我测试我的代码时,我发现有趣的行为让我感到困惑。解析Enum时出现混乱
使用下面的代码示例,有人可以阐明为什么在/ s当“s”变量的值与Enum值之一不匹配时不抛出异常?另外,如何将sEnum var设置为Stooge枚举定义中不存在的值?
class Program
{
enum Stooge
{
Unspecified,
Moe,
Larry,
Curly,
Shemp
}
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Enter a number...");
string s = Console.ReadLine();
Stooge sEnum = (Stooge)(int.Parse(s)); //Why doesn't this line throw if s != 0, 1, 2, 3, or 4?
Console.WriteLine("\r\nYou entered: {0}\r\nEnum String Value: {1}\r\nEnum Int Value: {2}\r\n", s, sEnum.ToString(), (int)sEnum);
}
}
}
可能重复的[为什么将int转换为无效的枚举值不抛出异常?](http://stackoverflow.com/questions/6413804/why-does-casting-int-to-invalid-enum-value-not -throw-exception) – nawfal 2013-12-01 19:39:11