索引器(Indexer)允许你像访问数组一样,通过索引访问对象的属性或数据。索引器的主要用途是在对象内部封装复杂的数据结构,使得数据访问更加直观。下面是关于 C# 索引器的详细解释及示例:

基本语法

索引器的语法类似于属性,但它使用方括号 [] 来定义索引参数。索引器通常定义在类或结构体内部。

public class MyClass
{
    private int[] data = new int[10];

    // 索引器的定义
    public int this[int index]
    {
        get
        {
            // 索引器的 getter 方法
            if (index < 0 || index >= data.Length)
                throw new IndexOutOfRangeException();
            return data[index];
        }
        set
        {
            // 索引器的 setter 方法
            if (index < 0 || index >= data.Length)
                throw new IndexOutOfRangeException();
            data[index] = value;
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
示例解释
  1. 定义索引器:
  • public int this[int index] 定义了一个接受整数索引的索引器。this 关键字表明这是一个索引器而不是普通的属性。
  1. Getter 和 Setter:
  • get 方法用于获取索引器的值。它检查索引是否在有效范围内,然后返回相应的值。
  • set 方法用于设置索引器的值。它检查索引是否在有效范围内,然后设置相应的值。
  1. 使用索引器:
  • 索引器可以像数组一样使用。例如:
MyClass obj = new MyClass();
obj[0] = 10;   // 调用索引器的 setter 方法
int value = obj[0]; // 调用索引器的 getter 方法
Console.WriteLine(value); // 输出 10
  • 1.
  • 2.
  • 3.
  • 4.
具有多个参数的索引器

索引器不仅可以有一个参数,还可以有多个参数。示例如下:

public class MultiDimensionalClass
{
    private int[,] data = new int[5, 5];

    // 多维索引器的定义
    public int this[int row, int col]
    {
        get
        {
            if (row < 0 || row >= data.GetLength(0) || col < 0 || col >= data.GetLength(1))
                throw new IndexOutOfRangeException();
            return data[row, col];
        }
        set
        {
            if (row < 0 || row >= data.GetLength(0) || col < 0 || col >= data.GetLength(1))
                throw new IndexOutOfRangeException();
            data[row, col] = value;
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
使用具有多个参数的索引器
MultiDimensionalClass obj = new MultiDimensionalClass();
obj[2, 3] = 42;   // 调用多维索引器的 setter 方法
int value = obj[2, 3]; // 调用多维索引器的 getter 方法
Console.WriteLine(value); // 输出 42
  • 1.
  • 2.
  • 3.
  • 4.