C#学习之利用泛型实现列表功能

引言:小生今日分享的是如何利用泛型来实现列表的功能,如果发现有描述错误,请评论告知,不甚感谢!
开发版本:VS 2017
适合人群:初学Unity者
开启学习之旅吧!

1 什么是泛型?

通过参数化类型来实现在同一份代码上操作多种数据类型,利用“参数化类型”将类型抽象化,实现代码的灵活复用。

(推荐泛型学习博客:https://www.cnblogs.com/hhzblogs/p/7820005.html)

2 实现功能

首先需要创建一个接口,规定要实现列表的方法
interface IListDS<T> 
    {
        //判断列表是否为空
        bool IsEmpty();
        //添加元素
        void Add(T item);
        //获取容量大小
        int GetCapacity();
        //在指定位置插入元素
        void Insert(int index,T item);
        //获取指定位置的元素
        T GetItem(int index);
        //通过索引器访问,修改元素
        T this[int index] { get; set; }
        //返回第一个该元素的索引
        int IndexOf(T item);
        //返回最后一个该元素的索引
        int LastIndexOf(T item);
        //对列表进行排序
        void Sort();
        //移除第一个该元素
        void Remove(T item);
        //移除指定位置的元素
        void RemoveAt(int index);
        //清空列表
        void Clear();
    }
新建一个NewList类,继承 IListDS<T> 接口,实现列表具体的功能
 class NewList<T> : IListDS<T> where T : IComparable//泛型约束
    {
        private T[] data;
        private int count;
        public int Count
        {
            get
            {
                return this.count;
            }
        }
        public int Capacity
        {
            get
            {
                return data.Length;
            }
        }
        public NewList(int size)
        {
            if (size >= 0)
            {
                data = new T[size];
            }
        }
        //定义一个无参构造函数,默认数组大小为0
        public NewList() : this(0) { }
        public T this[int index]
        {
            get
            {
                return GetItem(index);
            }
            set
            {
                if (index >= 0 && index <= Count - 1)
                {
                    data[index] = value;
                }
                else
                {
                    throw new Exception("IndexOutOfRangeException");
                }
            }
        }

        public void Add(T item)
        {
            if (Count == Capacity)
            {
                if (Capacity == 0)
                {
                    data = new T[4];
                }
                else
                {
                    T[] newArray = new T[Capacity * 2];
                    Array.Copy(data, newArray, Count);//复制前Count个元素到newArray
                    data = newArray;
                }
            }
            data[Count] = item;
            count++;
        }
        public int GetCapacity()
        {
            return Capacity;
        }
        public void Clear()
        {
            count = 0;
        }
        public T GetItem(int index)
        {
            if (index >= 0 && index <= Count - 1)
            {
                return data[index];
            }
            else
            {
                throw new Exception("IndexOutOfRangeException");
            }
        }
        public void Insert(int index, T item)
        {
            if (index >= 0 && index <= Count - 1)
            {
                if (Count == Capacity)//容量不够的情况,需先进行扩容
                {
                    if (Capacity == 0)
                    {
                        data = new T[4];
                    }
                    else
                    {
                        T[] newArray = new T[Capacity * 2];
                        Array.Copy(data, newArray, count);
                        data = newArray;
                    }
                }
                for (int i = count - 1; i >= index; i--)
                {
                    data[i + 1] = data[i];
                }
                data[index] = item;
                count++;
            }
            else
            {
                throw new Exception("IndexOutOfRangeException");
            }
        }
        public bool IsEmpty()
        {
            return count == 0;
        }
        public int IndexOf(T item)
        {
            for (int i = 0; i < count; i++)
            {
                if (item.Equals(data[i]))
                {
                    return i;
                }
            }
            return -1;
        }
        public int LastIndexOf(T item)
        {
            for (int i = count - 1; i >= 0; i--)
            {
                if (item.Equals(data[i]))
                {
                    return i;
                }
            }
            return -1;
        }
        public void Remove(T item)
        {
            for (int i = 0; i < Count; i++)
            {
                if (item.Equals(data[i]))
                {
                    RemoveAt(i);
                    break;
                }
            }
        }
        public void RemoveAt(int index)
        {
            if (index >= 0 && index <= Count - 1)
            {
                for (int i = index + 1; i < count; i++)
                {
                    data[i - 1] = data[i];
                }
                count--;
            }
            else
            {
                throw new Exception("IndexOutOfRangeException");
            }
        }
        public void Sort()
        {
            bool isOrder = false;
            do
            {
                isOrder = true;
                for (int i = 0; i < Count - 1; i++)
                {
                    if (data[i].CompareTo(data[i + 1]) > 0)
                    {
                        T temp = data[i + 1];
                        data[i + 1] = data[i];
                        data[i] = temp;
                        isOrder = false;
                    }
                }
            }
            while (!isOrder);
        }
    }
在Program类的Main方法类,检测列表功能是否正确
class Program
    {
        static void Main(string[] args)
        {
            NewList<string> strList = new NewList<string>();
            strList.Add("Hello");
            strList.Add("World");
            strList.Add("123");
            strList.Add("456");
            Console.WriteLine("Count:" + strList.Count + " Capacity:" + strList.Capacity);
            strList.Add("789");
            strList[4] = "777";
            strList.Insert(3,"777");
            strList.RemoveAt(1);
            strList.Remove("777");
            Console.WriteLine("Count:" + strList.Count + " Capacity:" + strList.Capacity);
            for (int i = 0; i < strList.Count; i++)
            {
                Console.Write(strList[i] + " ");
            }
            strList.Insert(0, "777");
            int index = strList.IndexOf("777");
            int lastIndex = strList.LastIndexOf("777");
            Console.WriteLine("\nIndex:" + index+" lastIndex:"+lastIndex);
            for (int i = 0; i < strList.Count; i++)
            {
                Console.Write(strList[i] + " ");
            }
            string isEmpty = strList.IsEmpty() ? "true" : "false";
            Console.WriteLine("\nisEmpty:" + isEmpty);
            strList.Clear();
            isEmpty = strList.IsEmpty() ? "true" : "false";
            Console.WriteLine("isEmpty:" + isEmpty);
            Console.WriteLine("Count:" + strList.Count + " Capacity:" + strList.Capacity);
            Console.ReadKey();
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_35361471/article/details/79379345