在 C# 编程中,索引器(Indexer) 是一个非常实用但初学者容易忽略的特性。它允许你像访问数组一样访问自定义类或结构体中的元素,从而提升代码的可读性和使用体验。本文将从零开始,带你深入理解 C#索引器 的原理,并通过实际示例演示如何在 自定义集合 中实现灵活的 C#集合访问 功能。

索引器是 C# 中一种特殊的属性,它允许对象使用 [] 运算符进行访问。你可以把它想象成“让类支持下标访问”的魔法语法。
例如,我们熟悉的 List<T> 或 Dictionary<K, V> 都内部使用了索引器:
List<string> names = new List<string>();names.Add("Alice");names.Add("Bob");// 通过索引器访问元素string first = names[0]; // "Alice"当你创建自己的集合类(比如学生列表、商品库存等)时,如果希望用户能像使用数组一样方便地读写数据,就需要实现索引器。这不仅能提升 API 的友好度,还能让你的 自定义集合 行为更贴近 .NET 内置集合。
索引器的定义方式类似于属性,但使用 this[参数] 作为名称:
public 类型 this[索引类型 index]{ get { /* 返回值 */ } set { /* 设置值 */ }}下面我们创建一个名为 MyStringCollection 的类,它内部使用 List<string> 存储数据,并通过索引器提供访问接口。
using System;using System.Collections.Generic;class MyStringCollection{ private List<string> _items = new List<string>(); // 索引器:通过整数索引访问 public string this[int index] { get { if (index < 0 || index >= _items.Count) throw new IndexOutOfRangeException("索引超出范围"); return _items[index]; } set { if (index < 0 || index >= _items.Count) throw new IndexOutOfRangeException("索引超出范围"); _items[index] = value; } } // 添加元素的方法 public void Add(string item) { _items.Add(item); } // 获取集合大小 public int Count => _items.Count;}使用方式如下:
class Program{ static void Main() { var collection = new MyStringCollection(); collection.Add("苹果"); collection.Add("香蕉"); Console.WriteLine(collection[0]); // 输出:苹果 collection[1] = "橙子"; Console.WriteLine(collection[1]); // 输出:橙子 }}索引器不仅限于整数索引!你还可以使用字符串、枚举等作为索引。例如,我们可以为同一个类添加一个基于字符串键的索引器:
// 在 MyStringCollection 类中新增private Dictionary<string, string> _namedItems = new Dictionary<string, string>();// 基于字符串键的索引器public string this[string key]{ get { if (_namedItems.TryGetValue(key, out string value)) return value; throw new KeyNotFoundException($"未找到键 '{key}'"); } set { _namedItems[key] = value; }}这样你就可以同时支持两种访问方式:
collection["水果"] = "西瓜";Console.WriteLine(collection["水果"]); // 输出:西瓜List<T>,建议直接继承 Collection<T> 或使用组合+接口(如 IList<T>),而非手动实现所有功能。通过本篇 索引器实现教程,你应该已经掌握了如何在 C# 中为自定义类添加索引器,从而实现类似数组的访问语法。无论是开发游戏道具系统、配置管理器,还是构建领域特定的集合类,索引器都能让你的代码更加优雅和直观。
记住,合理使用 C#索引器 不仅能提升用户体验,还能让你的 自定义集合 更加符合 .NET 的设计规范。快去试试吧!
本文由主机测评网于2025-12-21发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/20251211019.html