服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#中通过反射将枚举元素加载到ComboBo的实现方法

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

2022-12-06 11:25_平凡之路_ C#

本文主要介绍了C#中通过反射将枚举元素加载到ComboBo的实现方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

一、前言

       做过系统参数设置的同学们,肯定遇到过要提供一系列具有相同特点的选项供用户选择。最初级的做法是在窗体上增加一个下拉框控件,手工填写Items选项。然后运行时可以下拉选择。那如果有百八十个参数都是这种方式怎么办?

        上述做法弊端很明显。那么如何灵活的实现这个需求呢?

二、思路

        在代码中定义枚举类型,然后在窗体加载时,将枚举类型的元素(描述信息)加载到下拉框中,这样以后增加或修改了枚举元素后,下拉框中时刻保持的是最新的数据。再运用上反射机制,多个下拉框可以复用同一个加载方法。代码量会大幅度减少,同时可读性和可维护性提高了许多。

三、上代码

        1. 首先定义一个枚举,例如:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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的代码封装为静态方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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; }
    }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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赋予下拉框。

入参为下拉框、以及具体的枚举类型:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/// <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为之前定义的枚举类型: 

?
1
loadComboBoxItems(direction, typeof(Enum_Direction));

运行后效果如图:

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

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

到此这篇关于C#中通过反射将枚举元素加载到ComboBo的实现方法的文章就介绍到这了,更多相关C# 枚举加载到ComboBo内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/dangbochang/article/details/120523121

延伸 · 阅读

精彩推荐
  • C#C#七大经典排序算法系列(上)

    C#七大经典排序算法系列(上)

    这篇文章主要为大家详细介绍了C#七大经典排序算法系列上篇,冒泡排序,快速排序等,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    一线码农9152021-12-31
  • C#C#基于正则去掉注释的方法示例

    C#基于正则去掉注释的方法示例

    这篇文章主要介绍了C#基于正则去掉注释的方法,结合简单实例形式分析了C#针对注释符号的正则匹配相关操作技巧,需要的朋友可以参考下...

    何问起5472022-01-06
  • C#C# 元组和值元组的具体使用

    C# 元组和值元组的具体使用

    这篇文章主要介绍了C# 元组和值元组的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面...

    北田9612022-10-13
  • C#unity实现手机端摇杆控制人物移动

    unity实现手机端摇杆控制人物移动

    这篇文章主要为大家详细介绍了unity实现手机端摇杆控制人物移动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    魏恩君--Caroline8102022-08-31
  • C#C#往线程里传递参数的方法小结

    C#往线程里传递参数的方法小结

    这篇文章主要介绍了C#往线程里传参数的方法小结的相关资料,还给大家简单说明下传参的两种方式,非常不错,具有参考借鉴价值,需要的朋友可以参考下...

    瓦里奥5822021-12-02
  • C#c# 获得本地ip地址的三种方法

    c# 获得本地ip地址的三种方法

    这篇文章主要介绍了c# 获得本地ip地址的三种方法,帮助大家更好的理解和实用c#,感兴趣的朋友可以了解下...

    波多尔斯基10022022-10-24
  • C#C#基于Linq和反射实现数据持久化框架Xml4DB详解

    C#基于Linq和反射实现数据持久化框架Xml4DB详解

    在本篇文章里小编给大家整理的是关于C#基于Linq和反射实现数据持久化框架Xml4DB相关知识点,有需要的朋友们学习下。...

    PayneQin10042022-08-03
  • C#Unity中的Tilemap流程分析

    Unity中的Tilemap流程分析

    这篇文章给大家介绍Unity中的Tilemap流程分析,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友...

    boynextdoor9212022-11-24