C#中通过反射将枚举元素加载到ComboBo的实现方法

作者:_平凡之路_ 时间:2022-05-26 09:28:10 

一、前言

       做过系统参数设置的同学们,肯定遇到过要提供一系列具有相同特点的选项供用户选择。最初级的做法是在窗体上增加一个下拉框控件,手工填写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:

C#中通过反射将枚举元素加载到ComboBo的实现方法

5. 调用,参数1为下拉框控件名称,参数2的Enum_Direction为之前定义的枚举类型: 


loadComboBoxItems(direction, typeof(Enum_Direction));

运行后效果如图:

C#中通过反射将枚举元素加载到ComboBo的实现方法

如果有多个类似参数,每个只需一句代码调用即可。怎么样,是不是很方便?

来源:https://blog.csdn.net/dangbochang/article/details/120523121

标签:C#,枚举,加载,ComboBo
0
投稿

猜你喜欢

  • hadoop中实现java网络爬虫(示例讲解)

    2021-12-22 01:35:20
  • Java超全面梳理内部类的使用

    2021-09-06 11:24:07
  • 深入了解c# 迭代器和列举器

    2022-04-24 16:32:37
  • 深入了解Spring中最常用的11个扩展点

    2023-07-05 17:46:40
  • 各种格式的编码解码工具类分享(hex解码 base64编码)

    2021-11-17 07:04:51
  • Eclipse+Webservice简单开发实例

    2023-04-10 08:55:29
  • Java 8 中 Function 接口使用方法介绍

    2022-12-08 23:54:39
  • Spring Cloud Hystrix异常处理方法详解

    2022-05-29 06:20:12
  • C#获取真实IP地址实现方法

    2022-01-05 11:35:49
  • java实现微信红包 拼手气红包

    2023-09-28 10:31:45
  • java中JVM中如何存取数据和相关信息详解

    2023-08-10 03:49:46
  • mybatis 字段名自动转小写的实现

    2021-09-09 20:04:26
  • SpringBoot如何返回Json数据格式

    2023-01-12 16:28:51
  • 每日六道java新手入门面试题,通往自由的道路

    2023-11-13 16:22:29
  • Java中this关键字的用法详解

    2023-10-04 05:05:53
  • Java String 字符串常量池解析

    2023-01-08 19:44:05
  • springboot+springsecurity如何实现动态url细粒度权限认证

    2023-10-01 04:06:39
  • 基于java中cookie和session的比较

    2021-08-17 00:49:44
  • FasfDFS整合Java实现文件上传下载功能实例详解

    2022-05-27 02:30:46
  • SpringMVC 参数绑定相关知识总结

    2022-06-05 12:50:54
  • asp之家 软件编程 m.aspxhome.com