.net enum 忘備録

  • 静的Dictionary、enum
public static class Define
{
    public static Dictionary<string, int> TestDic =  new Dictionary<string,int>()
    {
        {"a",1},
        {"b",2},
        {"c",3}
    };

    public enum DATA_ITEM
    {
        営業 = 0,
        販売 = 10,
        開発 = 12,
    }
} 

public class EnumHelper
{
    public static string GetName(Type t, int val)
    {
        return Enum.GetName(t, val);
    }
 
    public static int GetValue(Type t, string key) 
    {
        return (int)Enum.Parse(t, key);
    }
 
    public static T GetName<T>(Type t, int val)
    {
        return (T)Enum.ToObject(t, val);
    }
 
    public static T GetValue<T>(Type t, string key) 
    {
        return (T)Enum.Parse(t, key);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(EnumHelper.GetName(typeof(Define.DATA_ITEM), 0));
     
        Console.WriteLine(EnumHelper.GetValue(typeof(Define.DATA_ITEM), "開発"));

        Define.DATA_ITEM dk = EnumHelper.GetName<Define.DATA_ITEM>(typeof(Define.DATA_ITEM), 0);
        Console.WriteLine("0:" + dk.ToString());
     
        Define.DATA_ITEM dv = EnumHelper.GetValue<Define.DATA_ITEM>(typeof(Define.DATA_ITEM), "開発");
        Console.WriteLine("開発:"+ dv.ToString());

        Console.WriteLine(Define.TestDic["a"].ToString());
        Console.ReadLine();
    }
}
  • comboboxへenumを設定
this.comboBox1.DataSource = Enum.GetNames(typeof(Define.DATA_ITEM));