索引器是C#中允许对象像数组一样通过方括号访问内部数据的特殊成员,使用this关键字定义,支持多种参数类型、重载及访问修饰符,需注意有效性检查与语义合理性。

索引器(Indexer)是 C# 中一种特殊的类成员,它允许对象像数组一样通过方括号 [] 来访问内部数据。有了索引器,你不需要调用专门的方法或暴露内部集合,就能直接“索引”对象,使用起来非常直观和自然。
索引器的基本语法
索引器的定义类似于属性,但使用 this 关键字来表示当前实例,并指定一个参数列表作为索引条件。
public 类型 this[参数类型 参数名]{
get
{
// 返回对应索引的值
}
set
{
// 设置对应索引的值
}
}
例如,定义一个简单的字符串容器类,让它支持按整数索引访问:
public class StringCollection{
private string[] items = new string[100];
public string this[int index]
{
get
{
if (index >= 0 && index < items.Length)
return items[index];
throw new IndexOutOfRangeException();
}
set
{
if (index >= 0 && index < items.Length)
items[index] = value;
else
throw new IndexOutOfRangeException();
}
}
}
使用方式就像操作数组一样:
var collection = new StringCollection();collection[0] = "Hello";
collection[1] = "World";
Console.WriteLine(collection[0]); // 输出: Hello
支持多种参数类型的索引器
索引器不限于使用整数作为索引。你可以定义以字符串或其他类型为参数的索引器,实现类似字典的行为。
public class PersonData{
private Dictionary
public string this[string key]
{
get => data.ContainsKey(key) ? data[key] : null;
set => data[key] = value;
}
}
这样就可以通过键名来读写数据:
var person = new PersonData();person["Name"] = "Alice";
person["Age"] = "30";
Console.WriteLine(person["Name"]); // 输出: Alice
索引器的重载
一个类可以定义多个索引器,只要它们的参数类型不同。比如同时支持 int 和 string 索引:
public class MixedCollection{
private string[] values = new string[10];
private Dictionary
public string this[int index]
{
get { return values[index]; }
set { values[index] = value; }
}
public string this[string key]
{
get { return map.ContainsKey(key) ? map[key] : null; }
set { map[key] = value; }
}
}
注意事项与最佳实践
虽然索引器很方便,但也需要注意以下几点:
- 不要滥用索引器,仅在语义上“像数组”或“像字典”时才使用
- 确保对索引参数进行有效性检查,避免越界或空引用异常
- 索引器可以有多个参数,例如二维索引:this[int x, int y]
- 索引器可以被设为 private 或 protected,用于内部封装
- 接口中也可以定义索引器,便于统一契约
基本上就这些。索引器让对象的访问更简洁、语义更清晰,是 C# 提供的一种优雅的语法糖。合理使用能显著提升代码可读性和易用性。










