当前位置: 首页 > news >正文

C# 枚举 扩展方法

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(){}
}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 【乐吾乐大屏可视化组态编辑器】数据绑定
  • Mac 连接 Synology NAS【Finder】
  • 【C语言篇】自定义类型:联合体和枚举详细介绍
  • 【django升级】django从2.2.6版本升级到3.2.25
  • 【ubuntu20.04 运行sudo apt-get upgrade报错】
  • 主机加固是什么?主机加固与产线工控安全关系
  • pg_stat_statements插件使用指南
  • NLP——文本预处理-新闻主题分类案例
  • MySQL——数据库的设计、事务、视图
  • GraalVM全面介绍:革新Java应用开发的利器
  • 【循环神经网络】案例:周杰伦歌词文本预测【训练+python代码】
  • 你真正了解低代码么?(国内低代码平台状况分析)
  • 华为od(D卷)最大N个数和最小N个数的和
  • 怎么用云手机进行TikTok矩阵运营
  • OpenTiny HUICharts 正式开源发布,一个简单、易上手的图表组件库
  • @jsonView过滤属性
  • JavaScript函数式编程(一)
  • javascript数组去重/查找/插入/删除
  • LeetCode算法系列_0891_子序列宽度之和
  • NSTimer学习笔记
  • oldjun 检测网站的经验
  • Python进阶细节
  • tweak 支持第三方库
  • 测试如何在敏捷团队中工作?
  • 得到一个数组中任意X个元素的所有组合 即C(n,m)
  • 基于阿里云移动推送的移动应用推送模式最佳实践
  • 紧急通知:《观止-微软》请在经管柜购买!
  • 漫谈开发设计中的一些“原则”及“设计哲学”
  • 推荐一个React的管理后台框架
  • 微信开放平台全网发布【失败】的几点排查方法
  • 无服务器化是企业 IT 架构的未来吗?
  • 吴恩达Deep Learning课程练习题参考答案——R语言版
  • 一、python与pycharm的安装
  • 译有关态射的一切
  • 东超科技获得千万级Pre-A轮融资,投资方为中科创星 ...
  • 浅谈sql中的in与not in,exists与not exists的区别
  • ​RecSys 2022 | 面向人岗匹配的双向选择偏好建模
  • ​TypeScript都不会用,也敢说会前端?
  • ‌JavaScript 数据类型转换
  • # centos7下FFmpeg环境部署记录
  • #经典论文 异质山坡的物理模型 2 有效导水率
  • (3)(3.5) 遥测无线电区域条例
  • (function(){})()的分步解析
  • (JS基础)String 类型
  • (Redis使用系列) Springboot 整合Redisson 实现分布式锁 七
  • (TOJ2804)Even? Odd?
  • (zt)最盛行的警世狂言(爆笑)
  • (附源码)ssm基于jsp的在线点餐系统 毕业设计 111016
  • (附源码)计算机毕业设计ssm本地美食推荐平台
  • (免费领源码)python+django+mysql线上兼职平台系统83320-计算机毕业设计项目选题推荐
  • (三) prometheus + grafana + alertmanager 配置Redis监控
  • (四) 虚拟摄像头vivi体验
  • (续)使用Django搭建一个完整的项目(Centos7+Nginx)
  • (一)Dubbo快速入门、介绍、使用
  • (一)pytest自动化测试框架之生成测试报告(mac系统)