我將字符串類型的數值轉換爲相應的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