List是常用的数据结构,大部分人都知道它是用数组实现的,
再稍微深入一点点,大部分也都知道List是如何进行扩容的,也就是:原容量*2
简单写一下List的解析,直接上代码了,我加了注释:
public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>
private const int _defaultCapacity = 4;//默认容量是定义好的4个
private T[] _items;//存储数据的数组
private int _size; //数组内数据的数量
private int _version; //版本号,用来区分版本是否一致,只要数组有修改就需要更新这个值
static readonly T[] _emptyArray = new T[0]; //一个定义好的空数组
//构造,一般都会走这个构造,把_emptyArray赋给了_items
public List() {
_items = _emptyArray;
}
//这是带参数的构造,创建一个指定长度的数组
public List(int capacity)
{
if (capacity < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity,
ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (capacity == 0)
_items = _emptyArray;
else
_items = new T[capacity];
}
//这是容器的大小字段
public int Capacity {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
//返回数组的长度,也就是容器大小的值
return _items.Length;
}
set {
//新值不能小于原数组里数据的长度
if (value < _size) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgum