C# 自定义List

这篇具有很好参考价值的文章主要介绍了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();
        }
    }
}

输出

C# 自定义List

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();
        }
    }
}

输出

C# 自定义List

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();
        }
    }
}

输出

C# 自定义List

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();
        }
    }
}

输出

C# 自定义List

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();
        }
    }
}

输出

C# 自定义List

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();
        }
    }
}

输出

C# 自定义List

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();
        }
    }
}

输出

C# 自定义List

结束

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

end文章来源地址https://www.toymoban.com/news/detail-423520.html

到了这里,关于C# 自定义List的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • vue 实现内容超出两行显示展开更多功能,可依据需求自定义任意行数!

    平时开发中我们经常会遇到这样的需求,在一个不限高度的盒子中会有很多内容,如果全部显示用户体验会非常不好,所以可以先折叠起来,当内容达到一定高度时,显示 展开更多 按钮, 点击即可显示全部内容 ,先来看看效果图:  这样做用户体验瞬间得到提升,接下来看

    2023年04月24日
    浏览(29)
  • <C++> list容器本质|常用接口|自定义排序规则

    ✅作者简介:热爱后端语言的大学生,CSDN内容合伙人 ✨精品专栏:C++面向对象 🔥系列专栏:C++泛型编程 🔥前言 今天把 list 容器的基本操作、常用接口做一个系统的整理,结合具体案例熟悉自定义内部排序方法的使用。 list 与 vector 是STL中最常用的两个容器,如果对vector

    2024年02月01日
    浏览(38)
  • 【C#学习笔记】数据类中常用委托及接口——以List<T>为例

    ListT为什么是神?在谈论这个问题之前,我想先说说其他数据表结构相较于ListT究竟差在了哪里…… 首先是 HashTable 本身呢就被 DictionaryTKey,TValue 完爆, HashTable 既不是线程安全的,也不是类型安全的,虽然提供了Synchronized()方法可以获取线程安全的类型,以为自己是个哈希表就

    2024年02月11日
    浏览(29)
  • 功能测试合集:弹出窗口的常用测试点,全程满满干豁

    前言 手机 App 弹窗是目前流行的一种内容展示形式,根据内容性质可以划分为消息、通知、广告、营销等等,展现形式也比较多变,刚上手 测试 特容易手忙脚乱,为了帮助新人能够快速入门,笔者在此将弹窗常见的测试点一一进行罗列,如果有所遗漏也请不吝指教,非常感

    2023年04月18日
    浏览(30)
  • Unity中Shader测试常用的UGUI功能简介

    我们在测试Shader效果时,可能会使用到一些简单的UGUI功能。在这篇文章我们大概的介绍一下UGUI的基础功能。 Unity的UGUI帮助文档 锚点是针对父级进行变换的。 锚点的作用是让UI适配不同设备的屏幕变换 需要修改为中心点模式 可以实现子对象 跟随 父对象 缩放的功能 我们在创

    2024年02月04日
    浏览(29)
  • ElasticSearch[八]:自定义评分功能、使用场景讲解以及 function_score常用的字段解释

    基本介绍 ES 的使用中,ES 会对我们匹配文档进行相关度评分。但对于一些定制化的场景,默认评分规则满足不了我们的要求。这些定制化场景,ES 也是推出了自定义评分方式来进行支持。可以使用 ES 提供的一些函数,什么可以使用较分来让我们的评分规则多样化。我举个大

    2024年01月24日
    浏览(30)
  • Python中的自定义密码验证,对密码验证功能进行单元测试(1)

    import unittest from app import is_valid_size class TestIsValidSize(unittest.TestCase): def test_empty_password(self): self.assertFalse(is_valid_size(“”)) def test_4_char_password(self): self.assertFalse(is_valid_size(“pass”)) def test_6_char_password(self): self.assertTrue(is_valid_size(“passwd”)) def test_16_char_password(self): self.assertTrue

    2024年04月23日
    浏览(37)
  • Unity中Shader测试常用的UGUI可交互功能的脚本基本使用

    我们在上篇文章简单介绍了一下Shader测试时常用的UGUI功能。 Unity中Shader测试常用的UGUI功能简介 我们在这篇文章中,简单看一下 可交互的UGUI的脚本怎么使用。 public Button _Button; void OnButtonClick() { Debug.Log(“你点击了按钮”); } _Button.onClick.AddListener(OnButtonClick); public Button _Button

    2024年02月04日
    浏览(32)
  • 人机交互-7-交互需求定义

    无论取代或更新已有系统,还是开发新产品,需求的建立都是非常重要的 需求获取是项目设计的第一个阶段 确定和记录现有的工作流程:收集 将信息组织起来,整体上涵盖工作的各个方面:描述 产品是不同的:对需求提出了特殊的要求 用户是不同的 人有不同的能力和弱点

    2023年04月20日
    浏览(33)
  • AutoSAR探秘:服务需求定义与arxml中服务的定义

    AutoSAR、入门、实战开发、服务需求、arxml、服务定义 AutoSAR,作为汽车电子领域的先进标准,涵盖众多方面,其中服务的需求定义和在arxml中的定义是我们深入研究的重要主题。本篇博客将聚焦于服务需求的定义以及在arxml中如何定义服务,通过案例和代码示例,带领读者深入

    2024年02月03日
    浏览(38)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包