C#之 List和泛型

概要:本文主要讲解了C#中的 List和泛型的使用,通过对List和泛型的理解然后自己自定义一个泛型集合类 CustomList.cs,实践果然是检验成果的唯一标准!哈哈哈!


一、语法介绍

1、List的创建和使用





2、



3、泛型概念



4、泛型定义




二、语法实践


//泛型类

namespace 列表List和泛型
{
    class GenericParadigm<T>
    {
        public T a;
        public T b;

        public GenericParadigm(T a, T b)
        {
            this.a = a;
            this.b = b;
        }

        public string GetSum()
        {
            return a + "" + b;
        }
    }
}



//使用泛型自定义List集合类

using System;

namespace 列表List和泛型
{
    class CustomList<T> where T:IComparable
    {
        private T[] array;//存储元素的数组
        private int count = 0;//集合的个数

        public int Count
        {
            get
            {
                return count;
            }
        }

        /// <summary>
        /// 指定List容量的构造函数
        /// </summary>
        /// <param name="size">容量</param>
        public CustomList(int size)
        {
            if (size >= 0)
            {
                array = new T[size];
            }
        }

        /// <summary>
        /// 构造一个初始容量为0的构造函数
        /// </summary>
        public CustomList()
        {
            array = new T[0];
        }

        /// <summary>
        /// List容量属性
        /// </summary>
        public int Capacity
        {
            get
            {
                return array.Length;
            }
        }

        /// <summary>
        /// 数据的添加
        /// </summary>
        /// <param name="item"></param>
        public void Add(T item)
        {
            //判断当前容量是否达到最大值
            if (Count == Capacity)
            {
                //初始容量为0,创建一个容量为4的新数组
                if (Capacity == 0)
                {
                    array = new T[4];
                }
                else
                {
                    var newArray = new T[Capacity * 2];//先创建一个容量为之前数组两倍的新数组
                    Array.Copy(array, newArray, Count);//将旧数组中的数据拷贝到新数组中
                    array = newArray;//将新数组中的数据再赋值给老数组
                }
            }
            array[Count] = item;
            count++;
        }


        /// <summary>
        /// 通过索引获取对应的元素
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public T GetItem(int index)
        {
            if (index >= 0 && index <= count -1)
            {
                return array[index];
            }
            else
            {
                throw new Exception("当前索引超出数组范围");
            }
        }

        /// <summary>
        /// 索引器:通过传递过来的索引对对应索引的元素进行获取和设置
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public T this[int index]
        {
            get
            {
                return GetItem(index);
            }
            set
            {
                if (index >= 0 && index <= count - 1)
                {
                    array[index] = value;
                }
                else
                {
                    throw new Exception("当前索引超出数组范围");
                }
            }
        }

        /// <summary>
        /// 列表中插入元素
        /// </summary>
        /// <param name="index"></param>
        /// <param name="item"></param>
        public void Insert(int index, T item)
        {
            //判断索引
            if (index >= 0 && index <= count - 1)
            {
                //判断容量
                if (Count == Capacity)
                {
                    var newArray = new T[Capacity * 2];
                    Array.Copy(array, newArray, Count);
                    array = newArray;
                }

                //从最后位置到要插入的位置遍历数组,目的是将索引位置的元素向后移
                for (int i = count - 1; i >= index; i--)
                {
                    array[i + 1] = array[i];
                }

                array[index] = item;//将新元素赋值给索引位置
                count++;//元素数量自增
            }
            else
            {
                throw new Exception("索引超出数组范围");
            }
        }

        /// <summary>
        /// 移除指定索引位置元素
        /// </summary>
        /// <param name="index"></param>
        public void RemoveAt(int index)
        {
            //判断索引
            if (index >= 0 && index <= count - 1)
            {
                //从索引位置向后一位到数组的末尾的位置遍历数组,目的是将索引位置的元素向前移
                for (int i = index + 1; i < count; i++)
                {
                    array[i - 1] = array[i];
                }
                count--;//元素数量自减
            }
            else
            {
                throw new Exception("索引超出数组范围");
            }
        }

        /// <summary>
        /// 从初始位置开始查找对应的元素
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public int IndexOf(T item)
        {
            for (int i = 0; i < count; i++)
            {
                if (array[i].Equals(item))
                {
                    return i;
                }
            }
            return -1;
        }

        /// <summary>
        /// 从最后位置向前查找相应的元素
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public int LastIndexOf(T item)
        {
            for (int i = count- 1; i >= 0; i--)
            {
                if (array[i].Equals(item))
                {
                    return i;
                }
            }
            return -1;
        }

        /// <summary>
        /// List排序
        /// </summary>
        public void Sort()
        {
            for (int i = 0; i < count - 1; i++)
            {
                for (int j = 0; j < count - 1; j++)
                {
                    if (array[j].CompareTo(array[j + 1]) > 0)
                    {
                        T temp = array[i];
                        array[i + 1] = array[i];
                        array[i] = temp;
                    }
                }
            }
        }
    }
}



//List和泛型实现类

using System;
using System.Collections.Generic;

namespace 列表List和泛型
{
    class Program
    {
        static void Main(string[] args)
        {
            //List的声明方式
            List<int> list1 = new List<int>();
            List<int> list2 = new List<int>(10);
            List<string> list3 = new List<string>() { "你好" , "世界" };

            //List容量和元素个数
            List<int> list4 = new List<int>();
            for (int i = 0; i < 20; i++)
            {
                Console.WriteLine("Capacity:" + list4.Capacity + " Count:" + list4.Count);
                list4.Add(i);
            }

            //List的遍历方式
            //for循环
            for (int i = 0; i < list4.Count; i++)
            {
                Console.WriteLine("for循环 list4[i]:" + list4[i]);
            }

            //foreach循环
            foreach (int item in list4)
            {
                Console.WriteLine("foreach循环 list4[item]:" + item);
            }

            //操作List属性和方法
            list4.Insert(5, 100);//插入
            int index1 = list4.IndexOf(8);//返回第一个匹配的值的索引
            int intdex2 = list4.LastIndexOf(15);//返回最后一个匹配的值的索引


            //泛型使用
            var generic1 = new GenericParadigm<int>(4, 5);
            Console.WriteLine("generic.GetSum() ==" + generic1.GetSum());

            var generic2 = new GenericParadigm<string>("在吗", "在呀");
            Console.WriteLine("generic.GetSum() ==" + generic2.GetSum());

            //泛型方法使用
            Console.WriteLine("SetPos() ==" + SetPos(12,34));
            Console.WriteLine("SetPos() ==" + SetPos(12.34, 34.56));
            Console.WriteLine("SetPos() ==" + SetPos("1245", "3467"));

            Console.WriteLine("GetAge() == " + GetAge<int, string, double, float>(4, "呵呵", 13.45, 8.94f));//类型也可以不指定

            Console.ReadKey();

        }

        /// <summary>
        /// 单个类型泛型方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        static string SetPos<T>(T a, T b)
        {
            return a + "" + b;
        }

        /// <summary>
        /// 多个泛型类型方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <typeparam name="T3"></typeparam>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="c"></param>
        /// <param name="d"></param>
        /// <returns></returns>
        static string GetAge<T, T1, T2, T3>(T a,T1 b ,T2 c,T3 d)
        {
            return a + "" + b + c + d;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/wanddoudou/article/details/80707880