讓自建類別像 List<>一樣也能 Add()、foreach

  • 786
  • 0
  • c#
  • 2016-02-17

摘要:MyCollection

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

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

            UserClass A1 = new UserClass(1, "A");
            UserClass B2 = new UserClass(2, "B");
            UserClassCollection userClasses = new UserClassCollection();
            userClasses.Add(A1);
            userClasses.Add(B2);

            foreach (UserClass uc in userClasses)
            {
                Debug.WriteLine(uc.i, uc.s);
            }

        }

        public class UserClass
        {
            public UserClass(int i, string s)
            {
                this.i = i;
                this.s = s;
            }

            public int i;
            public string s;
        }

        public class UserClassCollection : IEnumerable
        {
            List ies = new List();

            public UserClassCollection(UserClass[] userClassCollection)
            {
                this.ies = new List(userClassCollection);
            }

            public UserClassCollection()
            {
                // TODO: Complete member initialization
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                foreach (UserClass i in this.ies)
                {
                    yield return i;
                }
            }

            internal void Add(UserClass A1)
            {
                ies.Add(A1);
            }
        }

    }
}