C#中通過(guò)反射將枚舉元素加載到ComboBo的實(shí)現(xiàn)方法
一、前言
做過(guò)系統(tǒng)參數(shù)設(shè)置的同學(xué)們,肯定遇到過(guò)要提供一系列具有相同特點(diǎn)的選項(xiàng)供用戶選擇。最初級(jí)的做法是在窗體上增加一個(gè)下拉框控件,手工填寫(xiě)Items選項(xiàng)。然后運(yùn)行時(shí)可以下拉選擇。那如果有百八十個(gè)參數(shù)都是這種方式怎么辦?
上述做法弊端很明顯。那么如何靈活的實(shí)現(xiàn)這個(gè)需求呢?
二、思路
在代碼中定義枚舉類型,然后在窗體加載時(shí),將枚舉類型的元素(描述信息)加載到下拉框中,這樣以后增加或修改了枚舉元素后,下拉框中時(shí)刻保持的是最新的數(shù)據(jù)。再運(yùn)用上反射機(jī)制,多個(gè)下拉框可以復(fù)用同一個(gè)加載方法。代碼量會(huì)大幅度減少,同時(shí)可讀性和可維護(hù)性提高了許多。
三、上代碼
1. 首先定義一個(gè)枚舉,例如:
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>
/// 默認(rèn)值
/// </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. 引入模板方法,將枚舉轉(zhuǎn)換為L(zhǎng)ist的代碼封裝為靜態(tài)方法:
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>
/// 枚舉對(duì)象的值
/// </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>
/// 枚舉轉(zhuǎn)換為L(zhǎng)ist
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="startValue">從哪個(gè)一個(gè)元素開(kāi)始獲取</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. 封裝一個(gè)方法,通過(guò)反射將獲取到的List賦予下拉框。
入?yún)橄吕?、以及具體的枚舉類型:
/// <summary>
/// 加載下拉框選項(xiàng)
/// </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. 在窗體上設(shè)置一個(gè)下拉框,命名direction:
![]()
5. 調(diào)用,參數(shù)1為下拉框控件名稱,參數(shù)2的Enum_Direction為之前定義的枚舉類型:
loadComboBoxItems(direction, typeof(Enum_Direction));
運(yùn)行后效果如圖:

如果有多個(gè)類似參數(shù),每個(gè)只需一句代碼調(diào)用即可。怎么樣,是不是很方便?
到此這篇關(guān)于C#中通過(guò)反射將枚舉元素加載到ComboBo的實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)C# 枚舉加載到ComboBo內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Unity實(shí)現(xiàn)主角移動(dòng)與攝像機(jī)跟隨
這篇文章主要為大家詳細(xì)介紹了Unity實(shí)現(xiàn)主角移動(dòng)與攝像機(jī)跟隨,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-03-03
教你創(chuàng)建一個(gè)帶診斷工具的.NET鏡像
本文編寫(xiě)的初衷是因?yàn)樵谌豪镉泻芏嘈』锇橛龅缴a(chǎn)環(huán)境性能問(wèn)題的時(shí)候,.NET的runtime鏡像中沒(méi)有帶一些工具,安裝和使用起來(lái)很麻煩,所以分享一些我們公司內(nèi)部一些技巧,對(duì).NET鏡像帶診斷工具相關(guān)知識(shí)感興趣的朋友一起看看吧2022-07-07
C# 圖片與二進(jìn)制轉(zhuǎn)換的簡(jiǎn)單實(shí)例
這篇文章介紹了C# 圖片與二進(jìn)制轉(zhuǎn)換的簡(jiǎn)單實(shí)例,有需要的朋友可以參考一下2013-09-09
C# Onnx CenterNet實(shí)現(xiàn)目標(biāo)檢測(cè)的示例詳解
這篇文章主要為大家詳細(xì)介紹了C# Onnx CenterNet實(shí)現(xiàn)目標(biāo)檢測(cè)的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12
C#利用GDI+畫(huà)圖的基礎(chǔ)實(shí)例教程
編寫(xiě)圖形程序時(shí)需要使用GDI(Graphics Device Interface,圖形設(shè)備接口),所以通過(guò)網(wǎng)上的相關(guān)資料整理了這篇文章,下面這篇文章主要給大家介紹了關(guān)于C#利用GDI+畫(huà)圖基礎(chǔ)的相關(guān)資料,需要的朋友可以參考下。2018-04-04
c#之滾動(dòng)字幕動(dòng)畫(huà)窗體的實(shí)現(xiàn)詳解
本篇文章是對(duì)c#中滾動(dòng)字幕動(dòng)畫(huà)窗體的實(shí)現(xiàn)方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06

