C# 自定义List

目录

一、需求

二、List 常用功能

三、自定义List

四、测试

1.Add

2.Clear

3.Contains

4.IndexOf

5.Insert

6.Remove

7.RemoveAt

结束


一、需求

微软官方的 List 在命名空间 System.Collections.Generic 中,在平时的开发中 List 用的特别多,在用的时候我们基本不会考虑在 List 中内部是怎么写的,于是,我也写了一个List,想看看是否能实现和微软官方一样的功能,当然,不是说为了和微软比比谁写的好,也没那个必要,原创轮子等于白费功夫,微软的API基本已经优化的很好了,直接拿来用就行了,我写这篇文章目的只是为了更了解 List 内部的构造,提升自己 C# 基础,功能当然不可能有官方那么多。

二、List 常用功能

Capacity

        用于获取或设置List可容纳元素的数量。当数量超过容量时,这个值会自动增长。您可以设置这个值以减少容量,也可以调用trin()方法来减少容量以适合实际的元素数目。

Count

        获取List中当前元素数量

Item

        通过指定索引获取或设置元素。对于List类来说,它是一个索引器。

Add 

        在List中添加一个对象

AddRange

        在List尾部添加实现了ICollection接口的多个元素

BinarySearch 

        用于在排序的List内使用二分查找来定位指定元素.

Clear

        移除List所有元素

Contains

        测试一个元素是否在List内

CopyTo

        把一个List拷贝到一维数组内

Exists

        测试一个元素是否在List内

Find 

        查找并返回List内的出现的第一个匹配元素

FindAll

        查找并返回List内的所有匹配元素

GetEnumerator

        返回一个用于迭代List的枚举器

Getrange

        拷贝指定范围的元素到新的List内

IndexOf

        查找并返回每一个匹配元素的索引

Insert

        在List内插入一个元素

InsertRange

        在List内插入一组元素

LastIndexOf

        查找并返回最后一个匹配元素的索引

Remove

        移除与指定元素匹配的第一个元素

RemoveAt

        移除指定索引的元素

RemoveRange

        移除指定范围的元素

Reverse

        反转List内元素的顺序

Sort 

        对List内的元素进行排序

ToArray

        把List内的元素拷贝到一个新的数组内

三、自定义List

自定义 List 如下,我将常用的功能封装了一下

public class TList<T>
{
    private const int _defaultCapacity = 4;
    private static readonly T[] _emptyArray;
    private T[] _items;
    private int _size;
    private int _version;

    public int Capacity
    {
        get => this._items.Length;
        set
        {
            if (value < this._size)
            {
                throw new ArgumentOutOfRangeException("容量太小");
            }
            if (value != this._items.Length)
            {
                if (value > 0)
                {
                    T[] destinationArray = new T[value];
                    if (this._size > 0)
                    {
                        Array.Copy(this._items, 0, destinationArray, 0, this._size);
                    }
                    this._items = destinationArray;
                }
                else
                {
                    this._items = _emptyArray;
                }
            }
        }
    }
    
    public int Count => this._size;

    public T this[int index]
    {
        get
        {
            if (index >= this._size)
            {
                throw new ArgumentOutOfRangeException("index不能大于等于数组的长度");
            }
            return this._items[index];
        }
        set
        {
            if (index >= this._size)
            {
                throw new ArgumentOutOfRangeException("index不能大于等于数组的长度");
            }
            this._items[index] = value;
            this._version++;
        }
    }

    /// <summary>
    /// 添加对象到 List 中
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public int Add(object value)
    {
        if (this._size == this._items.Length)
        {
            this.EnsureCapacity(this._size + 1);
        }
        int index = this._size;
        this._size = index + 1;
        this._items[index] = (T)value;
        this._version++;
        return _size;
    }

    /// <summary>
    /// 从 List 中移除所有项
    /// </summary>
    public void Clear()
    {
        if (this._size > 0)
        {
            Array.Clear(this._items, 0, this._size);
            this._size = 0;
        }
        this._version++;
    }

    /// <summary>
    /// List 中是否包含指定的值
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    public bool Contains(object item)
    {
        if (item == null)
        {
            for (int j = 0; j < this._size; j++)
            {
                if (this._items[j] == null)
                {
                    return true;
                }
            }
            return false;
        }
        for (int i = 0; i < this._size; i++)
        {
            if (_items[i].Equals(item))
            {
                return true;
            }
        }
        return false;
    }

    /// <summary>
    /// 拷贝数组到 List 中指定的位置
    /// </summary>
    /// <param name="array"></param>
    /// <param name="arrayIndex"></param>
    public void CopyTo(T[] array, int arrayIndex)
    {
        Array.Copy(this._items, 0, array, arrayIndex, this._size);
    }

    /// <summary>
    /// 获取 List 中特定项的索引
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public int IndexOf(object value)
    {
        return Array.IndexOf<T>(this._items, (T)value, 0, this._size);
    }

    /// <summary>
    /// 从 List 中的指定索引处插入一个值
    /// </summary>
    /// <param name="index"></param>
    /// <param name="value"></param>
    public void Insert(int index, object value)
    {
        if (index > this._size)
        {
            throw new ArgumentOutOfRangeException("index不能大于数组长度");
        }
        if (this._size == this._items.Length)
        {
            this.EnsureCapacity(this._size + 1);
        }
        if (index < this._size)
        {
            Array.Copy(this._items, index, this._items, index + 1, this._size - index);
        }
        this._items[index] = (T)value;
        this._size++;
        this._version++;
    }

    /// <summary>
    /// 从 List 中移除特定对象的第一个匹配项
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    public bool Remove(T item)
    {
        int index = this.IndexOf(item);
        if (index >= 0)
        {
            this.RemoveAt(index);
            return true;
        }
        return false;
    }

    /// <summary>
    /// 移除位于指定索引处的 List 项。
    /// </summary>
    /// <param name="index"></param>
    public void RemoveAt(int index)
    {
        if (index >= this._size)
        {
            throw new ArgumentOutOfRangeException("index不能大于等于数组的长度");
        }
        this._size--;
        if (index < this._size)
        {
            Array.Copy(this._items, index + 1, this._items, index, this._size - index);
        }
        this._items[this._size] = default(T);
        this._version++;
    }

    private void EnsureCapacity(int min)
    {
        if (this._items.Length < min)
        {
            int num = (this._items.Length == 0) ? 4 : (this._items.Length * 2);
            if (num > 0x7fefffff)
            {
                num = 0x7fefffff;
            }
            if (num < min)
            {
                num = min;
            }
            this.Capacity = num;
        }
    }

    static TList()
    {
        _emptyArray = new T[0];
    }

    public TList()
    {
        this._items = _emptyArray;
    }

    public TList(int capacity)
    {
        if (capacity < 0)
        {
            throw new ArgumentOutOfRangeException("List长度不能小于0");
        }
        if (capacity == 0)
        {
            this._items = _emptyArray;
        }
        else
        {
            this._items = new T[capacity];
        }
    }
}

  

四、测试

1.Add

功能:向 List 内添加对象

namespace 计算1
{
    class Program
    {
        static void Main(string[] args)
        {
            TList<int> list = new TList<int>();
            list.Add(15);
            list.Add(62);
            list.Add(23);
            Console.WriteLine("长度:" + list.Count);
            Console.ReadKey();
        }
    }
}

输出

2.Clear

功能:清除 List 内所有的对象

namespace 计算1
{
    class Program
    {
        static void Main(string[] args)
        {
            TList<int> list = new TList<int>();
            list.Add(15);
            list.Add(62);
            list.Add(23);
            Console.WriteLine("长度:" + list.Count);
            list.Clear();
            Console.WriteLine("长度:" + list.Count);

            Console.ReadKey();
        }
    }
}

输出

3.Contains

功能:LIst 是否包含指定的值

namespace 计算1
{
    class Program
    {
        static void Main(string[] args)
        {
            TList<int> list = new TList<int>();
            list.Add(15);
            list.Add(62);
            list.Add(23);

            bool res = list.Contains(15);
            Console.WriteLine("是否包含:" + res);

            Console.ReadKey();
        }
    }
}

输出

4.IndexOf

功能:获取 List 中特定项的索引

namespace 计算1
{
    class Program
    {
        static void Main(string[] args)
        {
            TList<int> list = new TList<int>();
            list.Add(15);
            list.Add(62);
            list.Add(23);

            int index = list.IndexOf(23);
            Console.WriteLine("对应索引:" + index);

            Console.ReadKey();
        }
    }
}

输出

5.Insert

功能:从 List 中的指定索引处插入一个值

namespace 计算1
{
    class Program
    {
        static void Main(string[] args)
        {
            TList<int> list = new TList<int>();
            list.Add(15);
            list.Add(62);
            list.Add(23);
            //Console.WriteLine("长度:" + list.Count);

            list.Insert(1, 45);

            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i]);
            }

            Console.ReadKey();
        }
    }
}

输出

6.Remove

功能:从 List 中移除特定对象的一个匹配项

namespace 计算1
{
    class Program
    {
        static void Main(string[] args)
        {
            TList<int> list = new TList<int>();
            list.Add(15);
            list.Add(62);
            list.Add(23);
            list.Add(45);

            bool res = list.Remove(23);
            Console.WriteLine("移除结果:" + res);

            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i]);
            }

            Console.ReadKey();
        }
    }
}

输出

7.RemoveAt

功能:移除位于指定索引处的 List 项

namespace 计算1
{
    class Program
    {
        static void Main(string[] args)
        {
            TList<int> list = new TList<int>();
            list.Add(15);
            list.Add(62);
            list.Add(23);
            list.Add(45);

            list.RemoveAt(2);

            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i]);
            }

            Console.ReadKey();
        }
    }
}

输出

结束

如果这个帖子对你有用,欢迎 关注 + 点赞 + 留言,谢谢

end

  • 10
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

熊思宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值