Development/C#
Enum 변환
@위너스
2013. 2. 13. 19:52
static class Enum{ /// /// Enum을 Description으로 변형 /// /// Enum ///Description public static string ToDescription(Enum value) { DescriptionAttribute attribute = value.GetType() .GetField(value.ToString()) .GetCustomAttributes(typeof(DescriptionAttribute), false) .SingleOrDefault() as DescriptionAttribute; return attribute == null ? value.ToString() : attribute.Description; } ////// Enum을 EnumValue으로 변형 /// /// 을 ///EnumValue public static int? ToValue(Enum value) { return Convert.ToInt32(value); } ////// EnumString값을 Enum으로 변형 /// /// EnumString ///Enum public static T ToEnum(string value) { return (T)Enum.Parse(typeof(T), value); } ////// EnumString값을 EnumValue값으로 변형 /// /// ///EnumValue public static int? ToValue(string value) { try { return Convert.ToInt32(Enum.Parse(typeof(T), value)); } catch { return null; } } ////// Enum Description을 EnumValue로 변형 /// /// description ///EnumValue public static int? DescriptionToValue(string description) { try { return Convert.ToInt32(Enum.Parse(typeof(T), ToEnum(description).ToString())); } catch { return null; } } ////// Description을 Enum으로 변형 /// /// Description ///Enum public static T DescriptionToEnum(string description) { var type = typeof(T); if (!type.IsEnum) throw new ArgumentException(); FieldInfo[] fields = type.GetFields(); var field = fields.SelectMany(f => f.GetCustomAttributes(typeof(DescriptionAttribute), false), (f, a) => new { Field = f, Att = a }) .Where(a => ((DescriptionAttribute)a.Att).Description == description).SingleOrDefault(); return field == null ? default(T) : (T)field.Field.GetRawConstantValue(); } ////// EnumList값을 반환 /// ///EnumList public static IListGetValues() { IList list = new List (); foreach (var value in Enum.GetValues(typeof(T))) { list.Add((T)value); } return list; } }
테스트
enum ColorType
{
[Description("빨간색")]
Red,
[Description("녹색")]
Green,
[Description("파랑색")]
Blue
}
Enum<ColorType>.GetValues();
Enum<ColorType>.ToDescription(ColorType.Green);
Enum<ColorType>.ToValue(ColorType.Red);
Enum<ColorType>.ToEnum(ColorType.Red.ToString());
Enum<ColorType>.ToValue(ColorType.Red.ToString());
Enum<ColorType>.DescriptionToValue("빨간색");
Enum<ColorType>.DescriptionToEnum("빨간색");