출처 : https://qiita.com/mkuwan/items/be6745f2c9e7823f8a66
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
public static class TypeExtention { /// <summary> /// enumの値リストを取得 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static List<T> GetEnumList<T>(this Type type) where T : Enum { return Enum.GetValues(typeof(T)).Cast<T>().ToList(); } /// <summary> /// enumのDescripntionリストを取得 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static IEnumerable<string> GetEnumDescriptionEnumerable<T>(this Type type) where T : Enum { foreach (T value in Enum.GetValues(typeof(T))) yield return value.GetDescriptionFromValue(); } /// <summary> /// enumのDescripntionリストを取得 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static List<string> GetEnumDescriptionList<T>(this Type type) where T : Enum { List<string> descriptionList = new List<string>(); foreach (T value in Enum.GetValues(typeof(T))) descriptionList.Add(value.GetDescriptionFromValue()); return descriptionList; } } |
사용예
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
public enum SampleEnum { [Description("東京")] Tokyo = 1, [Description("名古屋")] Nagoya = 3, [Description("札幌")] Sapporo = 5, [Description("大阪")] Osaka = 7 } static void Test2() { Console.WriteLine("EnumExtention GetDescriptionFromValueを使ってTokyoのDescriptionを取得"); Console.WriteLine(SampleEnum.Tokyo.GetDescriptionFromValue()); Console.WriteLine(); Console.WriteLine("StringExtention GetEnumValueFromDescriptionを使ってDescriptionからenum値を取得"); Console.WriteLine("名古屋".GetEnumValueFromDescription<SampleEnum>()); Console.WriteLine(); Console.WriteLine("IntExtention GetEnumDescriptionFromIntを使ってint値からDescriptionを取得"); var sapporo = ((int)5).GetEnumDescriptionFromInt<SampleEnum>(); Console.WriteLine(sapporo); Console.WriteLine(); Console.WriteLine("IntExtention GetEnumValueFromIntを使ってint値からenum値を取得"); var osaka = ((int)7).GetEnumValueFromInt<SampleEnum>(); Console.WriteLine(osaka); Console.WriteLine(); Console.WriteLine("TypeExtention GetEnumListを使ってenumの値リストを取得"); var enumValues = typeof(SampleEnum).GetEnumList<SampleEnum>(); foreach (var e in enumValues) Console.WriteLine(e); Console.WriteLine(); Console.WriteLine("TypeExtention GetEnumDescriptionListを使ってDescriptionリストを取得"); var enumDescriptions = typeof(SampleEnum).GetEnumDescriptionList<SampleEnum>(); foreach (var e in enumDescriptions) Console.WriteLine(e); Console.WriteLine(); Console.WriteLine("TypeExtention GetEnumDescriptionEnumerableを使ってDescriptionリストを取得"); var enumDescriptionsEnumerable = typeof(SampleEnum).GetEnumDescriptionEnumerable<SampleEnum>(); foreach (var e in enumDescriptionsEnumerable) Console.WriteLine(e); Console.ReadLine(); } |