C# 中自定义泛型类的示例

一、自定义泛型类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpOOP_Lesson4
{

    /// <summary>
    /// 下拉框类
    /// </summary>
    public class CompBox<T>
    {

        public string ItemText
        {
            get;
            set;
        }

        public T ItemValue
        {
            get;
            set;
        }
    }
}

二、实体类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpOOP_Lesson4
{
    /// <summary>
    /// 程序员类
    /// </summary>
    public class SE
    {

        /// <summary>
        /// 工号
        /// </summary>
        public string ID { get; set; }


        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }
    }
}

 

三、应用

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CSharpOOP_Lesson4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            List<CompBox<SE>> list = new List<CompBox<SE>>();
            SE se = new SE();
            se.Name = "jack";
            se.ID = "10000";

            // 下拉框对象
            CompBox<SE> comp = new CompBox<SE>();
            comp.ItemText = "jack";
            comp.ItemValue = se;

            // 下拉框对象1
            CompBox<SE> comp1 = new CompBox<SE>();
            comp1.ItemText = "mary";
            comp1.ItemValue = se;

            list.Add(comp);
            list.Add(comp1);

            // 绑定集合
            comboBox1.DataSource = list;
            // 显示
            comboBox1.DisplayMember = "ItemText";
            //
            comboBox1.ValueMember = "ItemValue";
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 选择项
            var se = (CompBox<SE>)this.comboBox1.SelectedItem;
        }
    }
}

 

posted @ 2017-08-29 11:25  xiaobudong  阅读(578)  评论(0编辑  收藏  举报