C#中的索引器是一种特殊的类成员,它允许类的实例像数组一样通过索引值来访问内部的元素,这种设计让自定义集合的访问方式更加直观,不需要额外调用繁琐的获取或设置方法。

什么是C#索引器
索引器类似于类的属性,但它通过参数来标识要访问的元素,而不是通过属性名。索引器可以让对象使用方括号加索引值的方式直接获取或修改内部数据,最常见的应用场景就是自定义集合类。
和普通属性不同,索引器没有名称,在定义时使用this关键字作为标识,后面跟上方括号内的索引参数。索引器的参数类型可以是整数、字符串或者其他自定义类型,具体根据集合的存储结构来决定。
索引器的基本定义语法
定义索引器需要指定访问修饰符、返回值类型,以及this关键字和索引参数,同时需要实现get和set访问器来处理元素的读取和修改逻辑。
下面是一个简单的自定义字符串集合类,其中定义了整数类型的索引器,用来访问集合内部的字符串元素:
using System;
using System.Collections.Generic;
namespace IndexerDemo
{
// 自定义字符串集合类
public class StringCollection
{
// 内部存储字符串的列表
private List<string> _items = new List<string>();
// 定义整数类型的索引器
public string this[int index]
{
get
{
// 索引越界检查
if (index < 0 || index >= _items.Count)
{
throw new IndexOutOfRangeException($"索引 {index} 超出集合范围");
}
return _items[index];
}
set
{
if (index < 0 || index >= _items.Count)
{
throw new IndexOutOfRangeException($"索引 {index} 超出集合范围");
}
_items[index] = value;
}
}
// 添加元素的方法
public void Add(string item)
{
_items.Add(item);
}
// 获取集合元素数量
public int Count
{
get { return _items.Count; }
}
}
}
使用索引器简化集合访问
在没有索引器的情况下,如果要访问自定义集合的元素,通常需要定义GetItem、SetItem这类方法,调用时需要写完整的函数名和参数,操作不够简洁。
使用上面定义的StringCollection类,对比两种访问方式的差异:
传统方法访问集合
// 传统方式需要额外定义访问方法
public class OldStringCollection
{
private List<string> _items = new List<string>();
public string GetItem(int index)
{
return _items[index];
}
public void SetItem(int index, string value)
{
_items[index] = value;
}
public void Add(string item)
{
_items.Add(item);
}
}
// 调用方式
var oldCollection = new OldStringCollection();
oldCollection.Add("第一个元素");
oldCollection.Add("第二个元素");
// 获取元素需要调用方法
string firstItem = oldCollection.GetItem(0);
// 修改元素需要调用方法
oldCollection.SetItem(0, "修改后的第一个元素");
使用索引器访问集合
var collection = new StringCollection();
collection.Add("第一个元素");
collection.Add("第二个元素");
// 像数组一样直接通过索引获取元素
string firstItem = collection[0];
// 像数组一样直接通过索引修改元素
collection[0] = "修改后的第一个元素";
Console.WriteLine(collection[0]); // 输出:修改后的第一个元素
可以看出,使用索引器之后,集合的访问方式和系统内置的数组、List<T>等集合完全一致,不需要记忆额外的方法名,代码可读性更高,操作也更简洁。
索引器的其他常见用法
索引器的参数类型不局限于整数,还可以根据需求定义其他类型的参数,比如字符串索引器,适合通过键名访问集合元素的场景:
public class StudentCollection
{
private Dictionary<string, string> _students = new Dictionary<string, string>();
// 定义字符串类型的索引器,通过学生ID访问学生姓名
public string this[string studentId]
{
get
{
if (_students.ContainsKey(studentId))
{
return _students[studentId];
}
return null;
}
set
{
_students[studentId] = value;
}
}
public void AddStudent(string id, string name)
{
_students[id] = name;
}
}
// 使用方式
var studentCollection = new StudentCollection();
studentCollection.AddStudent("S001", "张三");
// 通过学生ID直接获取姓名
string name = studentCollection["S001"];
Console.WriteLine(name); // 输出:张三
另外,索引器也可以只定义get访问器,实现只读的集合访问,避免元素被意外修改:
public class ReadOnlyCollection
{
private int[] _data = { 1, 2, 3, 4, 5 };
// 只读索引器,只有get访问器
public int this[int index]
{
get
{
if (index < 0 || index >= _data.Length)
{
throw new IndexOutOfRangeException();
}
return _data[index];
}
}
}
索引器的使用注意事项
- 索引器的参数类型需要根据集合的实际存储结构来设计,整数索引适合顺序存储的集合,字符串或其他类型索引适合键值对结构的集合。
- 需要在索引器的
get和set访问器中做好参数校验,比如索引越界检查,避免运行时出现异常。 - 索引器不能被定义为静态成员,只能用于类的实例,这一点和普通的属性、方法有所区别。
- 如果一个类定义了多个不同参数类型的索引器,属于索引器重载,调用时会根据传入的参数类型自动匹配对应的索引器。
总的来说,C#的索引器通过让对象支持方括号索引访问的方式,消除了自定义集合访问时需要调用特定方法的繁琐步骤,让集合操作更加符合开发者的使用习惯,大幅简化了集合访问的代码逻辑,是自定义集合类时非常实用的特性。