C#数据结构List简单解析

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值