[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Enum)] public class EnumSignAttribute : Attribute { // Fields private string _displayName; public EnumSignAttribute(string displayname) { this._displayName = displayname; } // Properties public string DisplayName { get { return this._displayName; } set { this._displayName = value; } } }
public enum DataType { [EnumSign("布尔类型")] Boolean = 4, [EnumSign("日期时间")] DateTime = 3, None = 0, [EnumSign("数字")] Numberic = 2, [EnumSign("字符串")] String = 1 }
public static class EnumsUtils { ////// 根据object类型的数据,获取枚举类型 /// ////// /// public static T ConvertToEnum (object enumValue) { if (enumValue is int) { return (T)enumValue; } Type type = typeof(T); FieldInfo[] fields = type.GetFields(); int num = 0; foreach (FieldInfo info in fields) { if (num == 0) { num++; } else { T local = (T)info.GetValue(type); if (local.ToString().Equals(enumValue)) { return local; } } } return default(T); } /// /// 根据枚举标识,获取显示名字 /// ////// 枚举标识 /// 显示名字 public static string GetAttriValue(T enumValue) { Type type = typeof(T); FieldInfo[] fields = type.GetFields(); int num = 0; foreach (FieldInfo info in fields) { if (num == 0) { num++; } else { T local = (T)info.GetValue(type); if (local.Equals(enumValue)) { return GetDisplayName(info); } } } return string.Empty; } private static string GetDisplayName(FieldInfo field) { string displayName = string.Empty; object[] arr = field.GetCustomAttributes(typeof(EnumSignAttribute), true); if (arr.Length > 0) { EnumSignAttribute aa = (EnumSignAttribute)arr[0]; displayName = aa.DisplayName; } return displayName; } /// /// 获取枚举集合列表 /// /// ///public static EnumList GetSourceEnum(Type type) { EnumList list = new EnumList(); FieldInfo[] fields = type.GetFields(); foreach (FieldInfo field in fields) { EnumItem item = new EnumItem(); if (field.FieldType.IsEnum) { item.Value = ((int)type.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)); object[] arr = field.GetCustomAttributes(typeof(EnumSignAttribute), true); if (arr.Length > 0) { EnumSignAttribute aa = (EnumSignAttribute)arr[0]; item.Display = aa.DisplayName; } item.Name = field.Name; list.Add(item); } } return list; } } [StructLayout(LayoutKind.Sequential)] public struct EnumItem { private string _display; private string _name; private object _value; public EnumItem(string display, string name, object value) { this._display = display; this._name = name; this._value = value; } public string Display { get { return this._display; } set { this._display = value; } } public string Name { get { return this._name; } set { this._name = value; } } public object Value { get { return this._value; } set { this._value = value; } } }
public class EnumList : BindingList{ }//方法1:EnumList = EnumsUtils.GetSourceEnum.(typeof(DataType));//方法2:var = EnumsUtils.GetSourceEnum.(typeof(DataType));