文字列型の数値を対応する列挙型に変換しています。コードをテストしている間、私は混乱している面白い動作を発見しました。Enumの解析との混同
以下のコード例を使用して、「s」変数にEnum値の1つと一致しない値がある場合に、例外がスローされない理由を明らかにすることができますか?また、sEnum varをStooge enumの定義内に存在しない値に設定する方法はありますか?
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