首页 > 代码库 > 自制List<T>

自制List<T>

-----------------------------------------ListStu.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ConsoleApplication3
{
    public class ListStu<T>
    {
        private Queue<T> document = new Queue<T>();//实例队列,用来存放对象
        public T Add(T t)//添加
        {
            document.Enqueue(t);//向队列中添加对象
            return t;
        }
        public void Remove(int index)//删除索引
        {
            Queue<T> q = new Queue<T>();
            foreach (T item in document)
            {
                q.Enqueue(item);
            }
            document.Clear();//清空document
            int i = 0;
            foreach (T item in q)
            {
                if (index != i)
                {
                    document.Enqueue(item);
                }
                i++;
            }
            q.Clear();//清空q
        }
        public T this[int index] {//索引获取值
            get {
                int i = 0;
                foreach (T item in document)
                {
                    if (index == i)
                    {
                       return item;
                    }
                    i++;
                }
                return default(T);
            }
        }
        public IEnumerator<T> GetEnumerator()//迭代器
        {
            foreach (var item in document)
            {
                yield return item;
            }
        }
    }
}

-----------------------------------------主程序

 ListStu<Student> sss = new ListStu<Student>();
            sss.Add(new Student("张飞"));
            sss.Add(new Student("关羽"));
            sss.Remove(1);//移除关羽
            foreach (var item in sss)
            {
                Console.WriteLine(item.Name);//输出 张飞
            }
            Console.WriteLine();
            Console.WriteLine(sss[0].Name);//输出 张飞
            Console.ReadKey();

本文出自 “程序猿的家” 博客,请务必保留此出处http://962410314.blog.51cto.com/7563109/1528486

自制List<T>