在 C# 编程中,C#泛型集合 是处理不同类型数据的强大工具。虽然 .NET 提供了 List<T>、Dictionary<K,V> 等现成的集合类,但有时候我们需要更定制化的功能,比如限制元素数量、添加特定行为或优化性能。这时,自定义泛型集合 就派上用场了。
本教程将手把手教你如何从零开始创建一个简单的自定义泛型集合类,即使你是 C# 初学者也能轻松掌握!我们将围绕 MyList<T> 这个例子展开,逐步实现基本功能,并解释关键概念。

我们先创建一个最简单的泛型类,内部使用数组存储数据:
public class MyList<T>{ private T[] _items; private int _count; public MyList() { _items = new T[4]; // 初始容量为4 _count = 0; } public int Count => _count;}这里我们使用了泛型参数 T,意味着这个集合可以存储任何类型的数据。同时,我们维护了一个内部数组 _items 和一个计数器 _count。
接下来,我们添加向集合中插入元素的方法。当数组空间不足时,需要扩容:
public void Add(T item){ if (_count == _items.Length) { // 扩容:创建新数组,大小为原来的两倍 T[] newItems = new T[_items.Length * 2]; Array.Copy(_items, newItems, _items.Length); _items = newItems; } _items[_count] = item; _count++;}为了让集合像数组一样通过下标访问元素,我们实现索引器(Indexer):
public T this[int index]{ get { if (index < 0 || index >= _count) throw new IndexOutOfRangeException("索引超出范围"); return _items[index]; } set { if (index < 0 || index >= _count) throw new IndexOutOfRangeException("索引超出范围"); _items[index] = value; }}为了让我们的集合能被 foreach 遍历,需要实现 IEnumerable<T> 接口:
using System.Collections;using System.Collections.Generic;public class MyList<T> : IEnumerable<T>{ // ... 前面的代码 ... public IEnumerator<T> GetEnumerator() { for (int i = 0; i < _count; i++) { yield return _items[i]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }}现在,我们可以这样使用我们自定义的集合:
class Program{ static void Main() { var myList = new MyList<string>(); myList.Add("苹果"); myList.Add("香蕉"); myList.Add("橙子"); Console.WriteLine($"集合中有 {myList.Count} 个元素"); foreach (var fruit in myList) { Console.WriteLine(fruit); } // 通过索引访问 Console.WriteLine($"第一个水果是:{myList[0]}"); }}你还可以继续扩展这个集合,例如:
Remove、Clear、Contains 等方法IReadOnlyList<T> 接口以提高兼容性lock)通过这个简单的实践,你不仅掌握了 C#编程入门 中的关键技能,还深入理解了泛型和集合的工作原理。希望这篇 C#集合教程 能为你打下坚实的基础!
动手试试吧!编程最好的学习方式就是实践。
本文由主机测评网于2025-12-14发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/2025127742.html