C#中类的索引器

索引器允许类或结构的实例

就像数组一样进行索引。

索引器类似于属性,不同处在于它们的访问器采用参数。

索引器概述:

  • 使用索引器可以用类似于数组的方式为对象建立索引。
  • get 访问器返回值。 set 访问器分配值。
  • this 关键字用于定义索引器。
  • value 关键字用于定义由 set 索引器分配的值。
  • 索引器不必根据整数值进行索引,由您决定如何定义特定的查找机制。
  • 索引器可被重载。
  • 索引器可以有多个形参,例如当访问二维数组时。

下例中,定义了一个泛型类,并为其提供了简单的 getset 访问器方法

class SampleCollection<T>
{
    // Declare an array to store the data elements.
    private T[] arr = new T[100];

    // Define the indexer, which will allow client code
    // to use [] notation on the class instance itself.
    // (See line 2 of code in Main below.)       
    public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets
            // the corresponding element from the internal array.
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer.
class Program
{
    static void Main(string[] args)
    {
        // Declare an instance of the SampleCollection type.
        SampleCollection<string> stringCollection = new SampleCollection<string>();

        // Use [] notation on the type.
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}