namespace HW.Utility.Enums { using System; using System.Collections.Generic; using System.Windows.Forms; public static class EnumHelper { public static void BindEnumToComboBox(ComboBox cb) where T: struct { BindEnumToComboBox(cb, null, null); } public static void BindEnumToComboBox(ComboBox cb, string firstItemText, string firstItemValue) where T: struct { List> list = LoadEnum().ConvertAll>(delegate (KeyValuePair _input) { return new KeyValuePair(_input.Key.ToString(), (_input.Value != null) ? _input.Value.Description : _input.Key.ToString()); }); if ((firstItemText != null) && (firstItemValue != null)) { KeyValuePair item = new KeyValuePair(firstItemValue, firstItemText); list.Insert(0, item); } cb.DataSource = list; cb.DisplayMember = "Value"; cb.ValueMember = "Key"; } public static bool CheckIsTypeEnum(System.Type enumType, bool isThrowException) { if (enumType == null) { if (isThrowException) { throw new NullReferenceException(string.Format("类型参数{0}不能为空", "enumType")); } return false; } if (!enumType.IsEnum) { if (isThrowException) { throw new Exception(string.Format("类型{0}必须要为枚举", enumType.FullName)); } return false; } return true; } public static string LoadDescription(object obj) where T: struct { if (CheckIsTypeEnum(typeof(T), true)) { return LoadDescription((T) Enum.Parse(typeof(T), obj.ToString())); } return ""; } public static string LoadDescription(T t) where T: struct { string str = t.ToString(); foreach (KeyValuePair pair in LoadEnum()) { if (pair.Key.Equals(t)) { return pair.Value.Description; } } return str; } public static List> LoadEnum() where T: struct { Action action = null; List> list = new List>(); if (CheckIsTypeEnum(typeof(T), true)) { if (action == null) { action = delegate (T _enumData) { list.Add(new KeyValuePair(_enumData, EnumMapperAttribute.GetSelf(typeof(T).GetField(_enumData.ToString())))); }; } Array.ForEach(Enum.GetValues(typeof(T)) as T[], action); } return list; } public static T LoadEnumComboBoxCurrentSelect(ComboBox cb) where T: struct { T local = default(T); KeyValuePair selectedItem = (KeyValuePair) cb.SelectedItem; string key = selectedItem.Key; if (Enum.IsDefined(typeof(T), key)) { local = (T) Enum.Parse(typeof(T), key); } return local; } public static EnumMapperAttribute LoadMapper(object obj) where T: struct { return LoadMapper((T) Enum.Parse(typeof(T), obj.ToString())); } public static EnumMapperAttribute LoadMapper(T t) where T: struct { if (CheckIsTypeEnum(typeof(T), true)) { foreach (KeyValuePair pair in LoadEnum()) { if (pair.Key.Equals(t)) { return pair.Value; } } } return null; } } }