示例代碼: 執行結果圖: ...
示例代碼:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 11 namespace ReflectEnumDemo 12 { 13 //.NET支持的對稱(私匙加密)演算法類型 14 enum Encriptions 15 { 16 Aes, 17 DES, 18 RC2, 19 Rijndael, 20 TripleDES 21 } 22 23 public partial class MainForm : Form 24 { 25 public MainForm() 26 { 27 InitializeComponent(); 28 29 this.Load += (object sender, EventArgs e) => 30 { 31 Type type = typeof(Encriptions); 32 var enumValues = type.GetEnumValues(); //獲取所有枚舉值 33 34 DataTable dataTable = new DataTable(); //表,為了與UI綁定 35 dataTable.Columns.AddRange(new DataColumn[2] { new DataColumn("Key", typeof(string)), new DataColumn("Value", typeof(int)) }); //定義表欄位 36 37 foreach (var item in enumValues) 38 { 39 DataRow dataRow = dataTable.NewRow(); //定義行 40 dataRow["Key"] = type.GetEnumName(item); //列賦值 41 dataRow["Value"] = (int)item; 42 dataTable.Rows.Add(dataRow); //插入行 43 } 44 45 //cboShow是一個ComboxBox控制項 46 this.cboShow.DataSource = dataTable; //UI數據源,數據源必須是實現IList介面的類型 47 this.cboShow.ValueMember = "Value"; 48 this.cboShow.DisplayMember = "Key"; 49 }; 50 } 51 } 52 }
執行結果圖: