您的位置:首页 > 编程语言 > C#

C# :自己动手实现:使用数组的方式实现List

2017-11-16 17:07 453 查看
今天用List的时候突然想到。List在C#内部究竟是如何实现的

为什么可以动态增删元素,而数组不行,查了一下相关资料,发现大家实现的方式各不相同。

于是自己用了数组的方式实现了一个List

具体是实现方式其实数组也没有动态的变换长度,而是感觉用了一个障眼法的样子。弄了一个最大的容量和当前数组有效的长度

class MyList<T>
{
private T[] myArray;
private int size; //当前长度
private int capacity; //最大容量
public int Count { get { return size; } } //长度计数
public T this[int index] //索引器
{
get
{
return myArray[index];
}
set
{
myArray[index] = value;
}
}

public MyList()
{
size = 0;
capacity = 10;
myArray = new T[capacity];
}

public void Add(T n)
{
if (size == capacity)
{
capacity *= 2;
T[] tempArray = myArray;
myArray = new T[capacity];
tempArray.CopyTo(myArray, 0);
}
myArray[size] = n;
size += 1;
}

public void Insert(int index, T n)
{

if (size==capacity)
{
capacity *= 2;
}
for (int i = size; i > index; i--)
{
myArray[i] = myArray[i - 1];
}
myArray[index] = n;
size++;
}

public void RemoveAt(int index)
{
if (index<0&&index>size)
{
return;
}

for (int i = index; i <size-1; i++)
{
myArray[i] = myArray[i + 1];
}
myArray[size-1]=default(T);
size--;
}

public void Remove(T n)
{
for (int i = 0; i < myArray.Length; i++)
{
if (myArray[i].Equals(n))
{
RemoveAt(i);
}
}

}

}


特别简单的一串代码。没有做任何的异常处理。在删除数据后也没有做判断是否需要释放过多的空间
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c#