[C#]List泛型集合 範例

  • 6401
  • 0
  • C#
  • 2012-10-13

[C#]List泛型集合 範例

泛型的主要目的是讓程式碼更容易重複,並且有強型別的特性可以避免程式處理時,發生Boxing/Unboxing的問題

以下範例 示範List泛型集合的使用


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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private List<employee> employees = new List<employee>();

        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 加入到employees
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            employee emp=new employee(textBox1.Text,textBox2.Text);
            employees.Add(emp);
            textBox1.Clear();
            textBox2.Clear();
        }
        /// <summary>
        /// show出所有empid 及 empname
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            string allemp = "";
            foreach (var emps in employees)
            {
                 allemp += emps.ToString() + Environment.NewLine;
            }
            MessageBox.Show(allemp);
        }

        class employee
        {
            private string m_id;
            private string m_name;
            public employee(string id, string name)
            {
                m_id = id;
                m_name = name;
            }
            public override string ToString()
            {
                return "empId:" + m_id + "  empName:" + m_name;
            }
        }
    }
}


如有錯誤 歡迎指正