C# 中的索引器(Indexer)是什么 - 让对象支持类似数组的访问

来源:这里教程网 时间:2026-02-21 17:32:35 作者:

索引器(Indexer)是 C# 中一种特殊的类成员,它允许对象像数组一样通过方括号 [] 来访问内部数据。有了索引器,你不需要调用专门的方法或暴露内部集合,就能直接“索引”对象,使用起来非常直观和自然。

索引器的基本语法

索引器的定义类似于属性,但使用 this 关键字来表示当前实例,并指定一个参数列表作为索引条件。

public 类型 this[参数类型 参数名]
{
get
{
// 返回对应索引的值
}
set
{
// 设置对应索引的值
}
}

例如,定义一个简单的字符串容器类,让它支持按整数索引访问:

public class StringCollection
{
private string[] items = new string[100];

public string this[int index]<br>
{<br>
    get<br>
    {<br>
        if (index >= 0 && index < items.Length)<br>
            return items[index];<br>
        throw new IndexOutOfRangeException();<br>
    }<br>
    set<br>
    {<br>
        if (index >= 0 && index < items.Length)<br>
            items[index] = value;<br>
        else<br>
            throw new IndexOutOfRangeException();<br>
    }<br>
}<br>

}

使用方式就像操作数组一样:

var collection = new StringCollection();
collection[0] = "Hello";
collection[1] = "World";
Console.WriteLine(collection[0]); // 输出: Hello

支持多种参数类型的索引器

索引器不限于使用整数作为索引。你可以定义以字符串或其他类型为参数的索引器,实现类似字典的行为。

public class PersonData
{
private Dictionary data = new Dictionary();

public string this[string key]<br>
{<br>
    get => data.ContainsKey(key) ? data[key] : null;<br>
    set => data[key] = value;<br>
}<br>

}

这样就可以通过键名来读写数据:

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 map = new Dictionary();

public string this[int index]<br>
{<br>
    get { return values[index]; }<br>
    set { values[index] = value; }<br>
}<br><br>
public string this[string key]<br>
{<br>
    get { return map.ContainsKey(key) ? map[key] : null; }<br>
    set { map[key] = value; }<br>
}<br>

}

注意事项与最佳实践

虽然索引器很方便,但也需要注意以下几点:

不要滥用索引器,仅在语义上“像数组”或“像字典”时才使用 确保对索引参数进行有效性检查,避免越界或空引用异常 索引器可以有多个参数,例如二维索引:this[int x, int y] 索引器可以被设为 private 或 protected,用于内部封装 接口中也可以定义索引器,便于统一契约

基本上就这些。索引器让对象的访问更简洁、语义更清晰,是 C# 提供的一种优雅的语法糖。合理使用能显著提升代码可读性和易用性。

相关推荐

热文推荐