C# 枚举 扩展方法
功能
1.获取枚举描述
2.将指定枚举类型转换成List
3.将枚举类型转换成ListModel
4.绑定枚举
优点
1.一定编写随处可用。
2.调用代码简单,代码量少。
3.成熟代码无BUG
我是封装到DLL文件中,在具体的项目中引用。
调用
1、获取枚举列表 绑定到下列表中
//打标类型 下拉列表绑定数据
comboBoxMarkType.Items.Clear();
var markTypeEnumList = EnumExtension.GetEnumModelList(MarkTypeEnum.Array);
comboBoxMarkType.DataSource = markTypeEnumList;
comboBoxMarkType.DisplayMember = "Description";
comboBoxMarkType.ValueMember = "Val";
如果用不了可能是没有引用命名空间。
2.获取枚举的描述属性值
var valInt = int.Parse(val.ToString());
var markTypeEnumObj = (MarkTypeEnum)valInt;
MessageBox.Show(markTypeEnumObj.GetEnumDesc());
效果
引用命令空间
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
代码
/// <summary>
/// 枚举 扩展方法
/// </summary>
public static class EnumExtension
{
#region 属性定义
private static ConcurrentDictionary<string, ConcurrentDictionary<string, string>> _enumDic = new ConcurrentDictionary<string, ConcurrentDictionary<string, string>>();
private static readonly object objLock = new object();
#endregion
/// <summary>
/// 获取枚举描述
/// </summary>
/// <param name="e">任意枚举类型</param>
/// <returns>对应描述</returns>
public static string GetEnumDesc(this Enum e)
{
var description = string.Empty;
var fullName = e.GetType().FullName;
ConcurrentDictionary<string, string> descriptionDic = null;
if (_enumDic.TryGetValue(fullName, out descriptionDic))
{
descriptionDic.TryGetValue(e.ToString(), out description);
}
else
{
lock (objLock)
{
descriptionDic = new ConcurrentDictionary<string, string>();
foreach (var item in e.GetType().GetFields())
{
var enumAttributes = (DescriptionAttribute[])item.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (enumAttributes.Length > 0)
{
descriptionDic.TryAdd(item.Name, enumAttributes[0].Description);
}
}
_enumDic.TryAdd(fullName, descriptionDic);
descriptionDic.TryGetValue(e.ToString(), out description);
}
}
return description;
}
/// <summary>
/// 将指定枚举类型转换成List
/// </summary>
/// <param name="enumType">枚举类型</param>
/// <returns>以key/Val的方式返回枚举集合</returns>
public static List<KeyValuePair<string, int>> GetEnumKeyValueList(Type enumType)
{
return ConvertEnumToList(enumType);
}
/// <summary>
/// 将指定枚举类型转换成List
/// </summary>
/// <param name="enumType">枚举类型</param>
/// <returns>以key/Val的方式返回枚举集合</returns>
public static List<KeyValuePair<string, int>> ConvertEnumToList(Type enumType)
{
var list = new List<KeyValuePair<string, int>>();
if (enumType.IsEnum == false) { return null; }
var typeDescription = typeof(DescriptionAttribute);
var fields = enumType.GetFields();
foreach (var field in fields.Where(field => !field.IsSpecialName))
{
var strValue = field.GetRawConstantValue().ToString();
var arr = field.GetCustomAttributes(typeDescription, true);
var strText = arr.Length > 0 ? ((DescriptionAttribute)arr[0]).Description : field.Name;
var item = new KeyValuePair<string, int>(strText, Convert.ToInt32(strValue));
list.Add(item);
}
return list;
}
/// <summary>
/// 将枚举类型转换成ListModel
/// </summary>
/// <param name="enumType">枚举类型</param>
/// <returns>枚举集合</returns>
public static List<EnumModel> GetEnumModelList(Enum enumType)
{
return ConvertEnumModelToList(enumType);
}
/// <summary>
/// 将枚举类型转换成ListModel
/// </summary>
/// <param name="enumType">枚举类型</param>
/// <returns>枚举集合</returns>
public static List<EnumModel> ConvertEnumModelToList(Enum enumType)
{
var enumModelList = new List<EnumModel>();
var typeDescription = typeof(DescriptionAttribute);
var fields = enumType.GetType().GetFields();
foreach (var field in fields.Where(field => !field.IsSpecialName))
{
EnumModel model = new EnumModel();
model.Val = Convert.ToInt32(field.GetRawConstantValue());
model.Text = field.Name;
var arr = field.GetCustomAttributes(typeDescription, true);
model.Description = arr.Length > 0 ? ((DescriptionAttribute)arr[0]).Description : string.Empty;
enumModelList.Add(model);
}
return enumModelList;
}
/// <summary>
/// 绑定枚举
/// </summary>
/// <param name="typeInfo">枚举类型</param>
/// <param name="showDefault">显示默认</param>
/// <param name="selectValue">默认选中值</param>
/// <returns>列表项</returns>
public static List<SelectListItem> BindEnum(Type typeInfo, bool showDefault, string selectValue = "")
{
var enumItems = showDefault
? new List<SelectListItem> { new SelectListItem { Text = "---全部---", Value = "-1" } }
: new List<SelectListItem>();
var enumList = EnumExtension.ConvertEnumToList(typeInfo);
if (enumList != null && enumList.Any())
{
enumItems.AddRange(enumList.Select(p => new SelectListItem { Text = string.Format("---{0}---", p.Key), Value = p.Value.ToString() }));
if (!string.IsNullOrEmpty(selectValue))
{
foreach (var item in enumItems)
{
item.Selected = item.Value.Equals(selectValue);
}
}
}
return enumItems;
}
}
/// <summary>
/// 枚举对象
/// </summary>
public class EnumModel
{
/// <summary>
/// 属性值 例 Man
/// </summary>
public string Text { get; set; }
/// <summary>
/// INT 值 例 1
/// </summary>
public int Val { get; set; }
/// <summary>
/// Description 特性值 [Description("男")]
/// </summary>
public string Description { get; set; }
}
//
// 摘要:
// Represents the selected item in an instance of the System.Web.Mvc.SelectList
// class.
public class SelectListItem
{
//
// 摘要:
// Gets or sets a value that indicates whether this System.Web.Mvc.SelectListItem
// is selected.
//
// 返回结果:
// true if the item is selected; otherwise, false.
public bool Selected { get; set; }
//
// 摘要:
// Gets or sets the text of the selected item.
//
// 返回结果:
// The text.
public string Text { get; set; }
//
// 摘要:
// Gets or sets the value of the selected item.
//
// 返回结果:
// The value.
public string Value { get; set; }
//
// 摘要:
// Initializes a new instance of the System.Web.Mvc.SelectListItem class.
public SelectListItem()
{
}
}