いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

列挙体(Enum)値を動的に取得する (System.Enum.Parse)


Enumの値を動的に取得するには、以下のメソッドを利用します。

System.Enum.Parse(Type enumType, object value)


以下のようにして使用します。

//
// MessageBoxIconの値を動的に取得する。
//
foreach(string enumValue in new string[]{"Error", "Information", "Question"}){
    //
    // Enum値を取得.
    //
    MessageBoxIcon icon = (MessageBoxIcon) System.Enum.Parse(typeof(MessageBoxIcon), enumValue);

    MessageBox.Show("メッセージ", "キャプション", MessageBoxButtons.OK, icon);
}

基盤となるEnumのTypeオブジェクトも動的に取得する必要がある場合は

Type.GetType("System.Windows.Forms.MessageBoxIcon")

のようにすれば、全部が動的になりますね。