C# - 實作 Strongly Typed Custom Collections

摘要:C# - 實作 Strongly Typed Custom Collections

本篇主要是實作 Strongly Typed Custom Collections,這種方式其實早在 .Net Framework 1.0 的時代就已經存在,在 1.0 時代大多都是以繼承「CollectionBase」的寫法為主。之後隨著進入 .Net Framework 2.0 又有繼承「IList」或者「IEnumerable」等等的寫法。以下就來寫個簡單的 Sample 來實作...

步驟一:開個新的 WinForm 專案,並且將畫面佈置一下


步驟二:在專案中建立一個名為「MyRecord」的類別

Code:

using System.Collections;

namespace WindowsFormsApplication1
{
    public class MyRecord
    {
        private string _Key;
        private string _FirstName;
        private string _LastName;
        private string _Gender;

        public MyRecord()
        {
        }

        public MyRecord(string p_Key, string p_FirstName, string p_LastName, string p_Gender)
        {
            _Key = p_Key;
            _FirstName = p_FirstName;
            _LastName = p_LastName;
            _Gender = p_Gender;
        }

        public string Key
        {
            get { return _Key; }
            set { _Key = value; }
        }

        public string FirstName
        {
            get { return _FirstName; }
            set { _FirstName = value; }
        }

        public string LastName
        {
            get { return _LastName; }
            set { _LastName = value; }
        }

        public string Gender
        {
            get { return _Gender; }
            set { _Gender = value; }
        }

        public override string ToString()
        {
            return string.Format("{0} {1}:{2}", _FirstName, _LastName, _Gender);
        }
    }
}

步驟三:在專案中建立一個名為「MyRecords」的類別,這個類別一個「Strongly Typed Custom Collections」

Code:

using System.Collections;

namespace WindowsFormsApplication1
{
    public class MyRecords : CollectionBase
    {
        public MyRecords()
        {

        }

        public MyRecord this[int index]
        {
            get
            {
                return (MyRecord)this.List[index];
            }
            set
            {
                this.List[index] = value;
            }
        }

        public MyRecord this[string Key]
        {
            get
            {
                MyRecord _Result = null;

                foreach (MyRecord item in this.List)
                {
                    if (item.Key.Equals(Key))
                    {
                        _Result = item;
                        break;
                    }
                }

                return _Result;
            }
        }

        public int IndexOf(MyRecord item)
        {
            return base.List.IndexOf(item);
        }

        public int Add(MyRecord item)
        {
            foreach (MyRecord item1 in this.List)
            {
                if (item1.Key == item.Key) throw new Exception("Key 值重複!!!");
            }

            return this.List.Add(item);
        }

        public void Remove(MyRecord item)
        {
            this.InnerList.Remove(item);
        }

        public void CopyTo(Array array, int index)
        {
            this.List.CopyTo(array, index);
        }

        public void AddRange(MyRecords collection)
        {
            for (int i = 0; i < collection.Count; i++)
            {
                this.List.Add(collection[i]);
            }
        }

        public void AddRange(MyRecord[] collection)
        {
            this.AddRange(collection);
        }

        public bool Contains(MyRecord item)
        {
            return this.List.Contains(item);
        }

        public void Insert(int index, MyRecord item)
        {
            foreach (MyRecord item1 in this.List)
            {
                if (item1.Key == item.Key) throw new Exception("Key 值重複!!!");
            }

            this.List.Insert(index, item);
        }
    }
}

步驟四:在 WinForm 來使用「Strongly Typed Custom Collections」

Code:

namespace WindowsFormsApplication1
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MyRecord myRec = new MyRecord();
            myRec.FirstName = "小呆";
            myRec.LastName = "張";
            myRec.Gender = "男";

            MessageBox.Show(myRec.ToString());
        }

        private void button2_Click(object sender, EventArgs e)
        {
            StringBuilder sb = null;

            MyRecord KeyResult = null;

            MyRecords myRecs = new MyRecords();

            MyRecord myRec1 = new MyRecord();
            myRec1.Key = "DC";
            myRec1.FirstName = "小呆";
            myRec1.LastName = "張";
            myRec1.Gender = "男";
            myRecs.Add(myRec1);

            MyRecord myRec2 = new MyRecord();
            myRec2.Key = "EP";
            myRec2.FirstName = "小胖";
            myRec2.LastName = "邱";
            myRec2.Gender = "女";
            myRecs.Add(myRec2);

            MyRecord myRec3 = new MyRecord();
            myRec3.Key = "Ma";
            myRec3.FirstName = "大媽";
            myRec3.LastName = "張";
            myRec3.Gender = "女";

            MyRecord myRec5 = new MyRecord();
            myRec5.Key = "Bill";
            myRec5.FirstName = "小書";
            myRec5.LastName = "黃";
            myRec5.Gender = "男";

            #region 呈現 Collection 的全部資料

            myRecs.Add(myRec3);
            myRecs.Insert(1, myRec5);

            try
            {
                myRecs.Add(myRec5);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            sb = new StringBuilder();

            foreach (MyRecord item in myRecs)
            {
                sb.AppendLine(item.ToString());
            }

            MessageBox.Show(sb.ToString());
           
            #endregion

            #region 將刪除後的 Collection 的資料呈現出來

            myRecs.Remove(myRec5);

            sb = new StringBuilder();

            foreach (MyRecord item in myRecs)
            {
                sb.AppendLine(item.ToString());
            }

            MessageBox.Show(sb.ToString());

            #endregion

            #region 使用 Key 的方式找出符合的資料

            KeyResult = myRecs["EP"];

            if (KeyResult != null)
            {
                MessageBox.Show(KeyResult.ToString());
            }
            else
                MessageBox.Show("資料不存在!!!");

            KeyResult = myRecs["Bill"];

            if (KeyResult != null)
            {
                MessageBox.Show(KeyResult.ToString());
            }
            else
                MessageBox.Show("資料不存在!!!");

            #endregion

            #region 使用 Index 的方式找出符合的資料

            KeyResult = myRecs[2];

            MessageBox.Show(KeyResult.ToString());

            #endregion
        }
    }
}

結果:請自行執行成是觀看結果,謝謝!!!

參考:
CollectionBase 類別
(原創) 如何建立自己的Collection? (.NET) (C#) (C++/CLI) (C/C++)
Creating Strongly Typed Custom Collections in C#
Custom Collection in C# - Part 1 A Strongly Typed Custom Collection with C#