1、定义自己的IMyList接口
namespace DataStructure
{
public interface IMyList<T>
{
T this[int index] { get; set; }
void Add(T value);
bool Contains(T value);
void Clear();
int IndexOf(T value);
void Insert(int index, T value);
bool Remove(T value);
void RemoveAt(int index);
int Count { get; }
}
}
2、定义自己的MyList实现IMyList接口
using System;
namespace DataStructure
{
public class MyList<T>:IMyList<T>
{
private readonly T[] _items;
private readonly int _maxLength;
public int Count { get; private set; }
public T this[int index]
{
get => _items[index];
set => _items[index] = value;
}
public MyList(int maxLength)
{
Count = 0;
_items=new T[maxLength];
_maxLength = maxLength;
}
public void Add(T value)
{
if (Count+1 > _maxLength)
{
throw new Exception("超过定义的最大长度了");
}
_items[Count] = value;
Count++;
}
public bool Contains(T value)
{
for (var i = 0; i < Count; i++)
{
if (value .Equals(_items[i]))
{
return true;
}
}
return false;
}
public void Clear()
{
Count = 0;
}
public int IndexOf(T value)
{
for (var i = 0; i < Count; i++)
{
if (value .Equals(_items[i]))
{
return i;
}
}
return -1;
}
public void Insert(int index, T value)
{
if (Count+1 > _maxLength)
{
throw new Exception("超过定义的最大长度了");
}
if (index < 0)
{
throw new Exception("index不能为负数");
}
for (var i = Count-1; i >= index; i--)
{
_items[i + 1] = _items[i];
}
_items[index] = value;
Count++;
}
//返回true说明List中包含了value值,返回false说明List中没有value值
public bool Remove(T value)
{
var index=IndexOf(value);
if (index <= -1) return false;
RemoveAt(index);
return true;
}
public void RemoveAt(int index)
{
if (index < 0)
{
throw new Exception("index不能为负数");
}
if (index >= Count)
{
throw new Exception("index超过了当前数组的最大角标了");
}
for (var i = index; i < Count; i++)
{
_items[i]= _items[i + 1];
}
Count--;
}
public override string ToString()
{
var str="";
for (var i = 0; i < Count; i++)
{
str += _items[i].ToString()+" ";
}
return str;
}
}
}
注意:自己写的MyList的数组长度是固定的,那么程序集中的List是怎么实现可以增加任意个元素呢。查看List源码,来看看它的add方法是怎么实现的。注释部分实现内部数组动态扩展的核心部分。
public void Add(T item)
{
//这里当长度等于内置数组的长度时,扩大数组长度。
if (this._size == this._items.Length)
this.EnsureCapacity(this._size + 1);
this._items[this._size++] = item;
++this._version;
}
private void EnsureCapacity(int min)
{
if (this._items.Length >= min)
return;
//这里判断数组长度是否为0,为0就设置长度为4,不为0就是扩大数组长度为原来的两倍
int num = this._items.Length == 0 ? 4 : this._items.Length * 2;
if ((uint) num > 2146435071U)
num = 2146435071;
if (num < min)
num = min;
this.Capacity = num;
}
public int Capacity
{
[__DynamicallyInvokable] get
{
return this._items.Length;
}
[__DynamicallyInvokable] set
{
if (value < this._size)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
if (value == this._items.Length)
return;
if (value > 0)
{
T[] objArray = new T[value];
//这里将原来数组的数据复制到新的数组中。
if (this._size > 0)
Array.Copy((Array) this._items, 0, (Array) objArray, 0, this._size);
this._items = objArray;
}
else
this._items = List<T>._emptyArray;
}
}