C#中通过反射将枚举元素加载到ComboBo的实现方法
作者:_平凡之路_ 发布时间:2022-05-26 09:28:10
标签:C#,枚举,加载,ComboBo
一、前言
做过系统参数设置的同学们,肯定遇到过要提供一系列具有相同特点的选项供用户选择。最初级的做法是在窗体上增加一个下拉框控件,手工填写Items选项。然后运行时可以下拉选择。那如果有百八十个参数都是这种方式怎么办?
上述做法弊端很明显。那么如何灵活的实现这个需求呢?
二、思路
在代码中定义枚举类型,然后在窗体加载时,将枚举类型的元素(描述信息)加载到下拉框中,这样以后增加或修改了枚举元素后,下拉框中时刻保持的是最新的数据。再运用上反射机制,多个下拉框可以复用同一个加载方法。代码量会大幅度减少,同时可读性和可维护性提高了许多。
三、上代码
1. 首先定义一个枚举,例如:
using SharedBaseProject.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace SharedBaseProject.Common.CarPosition
{
public class Direction
{
/// <summary>
/// 方向
/// </summary>
public enum Enum_Direction
{
/// <summary>
/// 默认值
/// </summary>
[Description("未指定")]
None = -1,
/// <summary>
/// 上
/// </summary>
[Description("上")]
Up = 0,
/// <summary>
/// 下
/// </summary>
[Description("下")]
Down = 1,
/// <summary>
/// 左
/// </summary>
[Description("左")]
Left = 2,
/// <summary>
/// 右
/// </summary>
[Description("右")]
Right = 3
}
}
}
2. 引入模板方法,将枚举转换为List的代码封装为静态方法:
using System;
using System.Collections.Generic;
using System.Text;
namespace SharedBaseProject.CustomType
{
public class EnumberEntity
{
/// <summary>
/// 枚举的描述
/// </summary>
public string Description { set; get; }
/// <summary>
/// 枚举名称
/// </summary>
public string EnumName { set; get; }
/// <summary>
/// 枚举对象的值
/// </summary>
public int EnumValue { set; get; }
}
}
using SharedBaseProject.CustomType;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
namespace SharedBaseProject.Utils
{
public class EnumUtil
{
/// <summary>
/// 枚举转换为List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="startValue">从哪个一个元素开始获取</param>
/// <returns></returns>
public static List<EnumberEntity> EnumToList<T>(int startValue = 0)
{
List<EnumberEntity> list = new List<EnumberEntity>();
foreach (var e in Enum.GetValues(typeof(T)))
{
if (Convert.ToInt32(e) < startValue)
{
continue;
}
EnumberEntity m = new EnumberEntity();
object[] objArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);
if (objArr != null && objArr.Length > 0)
{
DescriptionAttribute da = objArr[0] as DescriptionAttribute;
m.Description = da.Description;
}
m.EnumValue = Convert.ToInt32(e);
m.EnumName = e.ToString();
list.Add(m);
}
return list;
}
}
}
3. 封装一个方法,通过反射将获取到的List赋予下拉框。
入参为下拉框、以及具体的枚举类型:
/// <summary>
/// 加载下拉框选项
/// </summary>
private void loadComboBoxItems(ComboBox comboBox, Type type, int startValue = 0)
{
// Get the generic type definition
MethodInfo method = typeof(EnumUtil).GetMethod("EnumToList", BindingFlags.Public | BindingFlags.Static);
// Build a method with the specific type argument you're interested in
method = method.MakeGenericMethod(type);
// The "null" is because it's a static method
List<EnumberEntity> listBaiduPositionMode = (List<EnumberEntity>)method.Invoke(null, new object[] { startValue });
if (listBaiduPositionMode == null || listBaiduPositionMode.Count < 1)
{
return;
}
int iCount = listBaiduPositionMode.Count;
for (int i = 0; i < iCount; i++)
{
comboBox.Items.Add(listBaiduPositionMode.ElementAt(i).Description);
}
}
4. 在窗体上设置一个下拉框,命名direction:
5. 调用,参数1为下拉框控件名称,参数2的Enum_Direction为之前定义的枚举类型:
loadComboBoxItems(direction, typeof(Enum_Direction));
运行后效果如图:
如果有多个类似参数,每个只需一句代码调用即可。怎么样,是不是很方便?
来源:https://blog.csdn.net/dangbochang/article/details/120523121


猜你喜欢
- 今年新开Java课程第一步就是…配置环境就从Java的环境配置开始好了以下是正式的步骤首先,从Oracle的官网下载jdk的安装包点我下载J
- 每一个基于java的应用程序都有一个共同工作来展示给用户看到的内容作为工作的应用几个对象。当编写一个复杂的Java应用程序,应用程序类应该尽
- 本文实例讲述了C#清除字符串内空格的方法,分享给大家供大家参考。具体如下:关键代码如下:/// <summary>/// 清除字
- 简评:Android Support Library 26 中终于实现了一个等待已久的功能: RecyclerView 的快速滚动 。And
- C# 中的每个类或结构都隐式继承 Object 类。因此,C# 中的每个对象都会获得 ToString 方法,此方法返回该对象的字符串表示形
- //把txt清空 &n
- 前情提要本文中提供了九种方式获取resources目录下文件的方式。其中打印文件的方法如下: /**
- 日常使用中spring的 @Cacheable 大家一定不陌生,基于aop机制的缓存实现,并且可以选择cacheManager具体提供缓存的
- 现在很多第三方Launcher((如360Launcher,GoLauncher)带有iphone主题,相信玩Android的人大都知道。本
- 前言此文适合了解了es相关概念以及基础知识的同学阅读elasticsearch简介Elasticsearch是一个基于Lucene的搜索服务
- 简介Java 在 1.5 引入了泛型机制,泛型本质是参数化类型,也就是说变量的类型是一个参数,在使用时再指定为具体类型。泛型可以用于类、接口
- 生成指定范围内的随机数这个是最常用的技术之一,程序员希望通过随机数的方式来处理众多的业务逻辑,测试过程中也希望通过随机数的方式生成包含大量数
- 简介有时候会需要在c#特别是WPF环境下调用其他的程序,这类型的程序以命令行为执行环境,这里就说明下如何调用exe并传递参数一般有两种方法一
- Java xml出现错误 javax.xml.transform.TransformerException: java.lang.NullP
- 这篇文章将向大家展示Java编程利用socket多线程访问服务器文件代码示例,如果您想先了解Java多线程socket编程的基础知识,可以看
- 前几天在琢磨mybatis xml热加载的问题,原理还是通过定时扫描xml文件去跟新,但放到项目上就各种问题,由于用了mybatisplus
- 开发环境安装JDK和JRE下载安装文件并安装:jdk-8u11-windows-i586.exejre-8u11-windows-i586.
- 本文实例为大家分享了Android实现简单垂直进度条的具体代码,供大家参考,具体内容如下代码注释特别清晰,就不多解释了支持属性:progre
- 1.类成员与方法的可见性最小化举例:如果是一个private的方法,想删除就删除如果一个public的service方法,或者一个publi
- 本文实例讲述了Android编程使用android-support-design实现MD风格对话框功能。分享给大家供大家参考,具体如下:首先