C#中提供的List类
首先来看看List类,它是一个泛型(如果对泛型不理解的小伙伴,可以自行百度了解一下),在C#原生List类中的,定义了很多对泛型列表元素的操作的方法,
例如:
public void Add(T item) //添加泛型元素
public void RemoveAt(int index) //移除指定索引的泛型元素
public bool Contains(T item) //确定某泛型元素是否在列表中,在返回bool值True,不在返回bool值False
...
该类中还有很多方法,这次我选择先实现以上三个方法,其他方法可以基于以上三个方法推理写出.
自己写的MyList类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 实现一个List类
{
class MyList<T>
{
//容器
private T[] arr = new T[4];
//容量
public int Capacity { get { return arr.Length; } }
//元素总个数
public int Count { get; private set; }
//添加元素
public void Add(T item)
{
//如果容量不够用
if (Count == Capacity)
{
//创建新数组
T[] arr1 = new T[Capacity < 1000 ? Capacity * 2 : Capacity + 100];
//复制元素给新数组
arr.CopyTo(arr1, 0);
//替换引用
arr = arr1;
}
//添加元素
arr[Count++] = item;
}
//从指定位置移除
public void RemoveAt(int index)
{
//如果越界
if (index >= Count) throw new IndexOutOfRangeException();
//元素前移
for (int i = index; i <= Count - 2; i++)
{
arr[i] = arr[i + 1];
}
Count--;//总数减少
}
//是否包含
public bool Contains(T item)
{
for (int i = 0; i < Count; i++)
{
if (arr[i].Equals(item))//找到
{
return true;
}
}
return false;//未找到
}
//索引器
public T this[int index]
{
get
{
//如果索引超出范围,抛出异常
if (index >= Count) throw new IndexOutOfRangeException();//throw new Exception("索引超出范围");
else return arr[index];
}//例如 int a=arr[i]
set
{
//如果索引超出范围,抛出异常
if (index >= Count) throw new IndexOutOfRangeException();
else arr[index] = value;
}//例如 arr[i]=5;
}
}
}
这里需要定义一个在List类中存在的索引器,其声明格式是:
public T this[int index];
ps:终于知道是如何实现通过数组索引返回数组元素的了.(>_<)
测试类Program类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 实现一个List类
{
class Program
{
static void Main(string[] args)
{
MyList<int> list = new MyList<int>();
//添加元素
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
try
{
list.RemoveAt(5);//移除索引为5的元素,会抛出异常:数据越界
}
catch (Exception e)
{
Console.WriteLine("出现问题了...");//捕获异常,输出提示信息
}
//输出list列表元素
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
//判断list列表中是否包含整型元素5
Console.WriteLine(list.Contains(5));//返回True
Console.ReadKey();
}
}
}
在测试类中的主方法创建写好的MyList类对象,并且实现一下写好的方法.
看看结果
我们发现MyList类成功实现了List类中的以上三个方法.