索引器(C# 编程指南)Indexers (C# Programming Guide)

索引器允许类或结构的实例就像数组一样进行索引。Indexers allow instances of a class or struct to be indexed just like arrays. 无需显式指定类型或实例成员,即可设置或检索索引值。The indexed value can be set or retrieved without explicitly specifying a type or instance member. 索引器类似于属性,不同之处在于它们的访问器需要使用参数。Indexers resemble properties except that their accessors take parameters.

以下示例定义了一个泛型类,其中包含用于赋值和检索值的简单 getset 访问器方法。The following example defines a generic class with simple get and set accessor methods to assign and retrieve values. Program 类创建了此类的一个实例,用于存储字符串。The Program class creates an instance of this class for storing strings.

using System;

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

   // Define the indexer to allow client code to use [] notation.
   public T this[int i]
   {
      get { return arr[i]; }
      set { arr[i] = value; }
   }
}

class Program
{
   static void Main()
   {
      var stringCollection = new SampleCollection<string>();
      stringCollection[0] = "Hello, World";
      Console.WriteLine(stringCollection[0]);
   }
}
// The example displays the following output:
//       Hello, World.

备注

有关更多示例,请参阅相关部分For more examples, see Related Sections.

表达式主体定义Expression Body Definitions

索引器的 get 或 set 访问器包含一个用于返回或设置值的语句很常见。It is common for an indexer's get or set accessor to consist of a single statement that either returns or sets a value. 为了支持这种情况,表达式主体成员提供了一种经过简化的语法。Expression-bodied members provide a simplified syntax to support this scenario. 自 C# 6 起,可以表达式主体成员的形式实现只读索引器,如以下示例所示。Starting with C# 6, a read-only indexer can be implemented as an expression-bodied member, as the following example shows.

using System;

class SampleCollection<T>
{
   // Declare an array to store the data elements.
   private T[] arr = new T[100];
   int nextIndex = 0;
   
   // Define the indexer to allow client code to use [] notation.
   public T this[int i] => arr[i];
   
   public void Add(T value)
   {
      if (nextIndex >= arr.Length) 
         throw new IndexOutOfRangeException($"The collection can hold only {arr.Length} elements.");
      arr[nextIndex++] = value;
   }
}

class Program
{
   static void Main()
   {
      var stringCollection = new SampleCollection<string>();
      stringCollection.Add("Hello, World");
      System.Console.WriteLine(stringCollection[0]);
   }
}
// The example displays the following output:
//       Hello, World.

请注意,=> 引入了表达式主体,并未使用 get 关键字。Note that => introduces the expression body, and that the get keyword is not used.

自 C# 7.0 起,get 和 set 访问器均可作为表达式主体成员实现。Starting with C# 7.0, both the get and set accessor can be an implemented as expression-bodied members. 在这种情况下,必须使用 getset 关键字。In this case, both get and set keywords must be used. 例如:For example:

using System;

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

   // Define the indexer to allow client code to use [] notation.
   public T this[int i]
   {
      get => arr[i]; 
      set => arr[i] = value; 
   }
}

class Program
{
   static void Main()
   {
      var stringCollection = new SampleCollection<string>();
      stringCollection[0] = "Hello, World.";
      Console.WriteLine(stringCollection[0]);
   }
}
// The example displays the following output:
//       Hello, World.

索引器概述Indexers Overview

  • 使用索引器可以用类似于数组的方式为对象建立索引。Indexers enable objects to be indexed in a similar manner to arrays.

  • get 取值函数返回值。A get accessor returns a value. set 取值函数分配值。A set accessor assigns a value.

  • this 关键字用于定义索引器。The this keyword is used to define the indexer.

  • value 关键字用于定义 set 索引器所赋的值。The value keyword is used to define the value being assigned by the set indexer.

  • 索引器不必根据整数值进行索引;由你决定如何定义特定的查找机制。Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.

  • 索引器可被重载。Indexers can be overloaded.

  • 索引器可以有多个形参,例如当访问二维数组时。Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.

相关部分Related Sections

C# 语言规范C# Language Specification

有关详细信息,请参阅 C# 语言规范中的索引器For more information, see Indexers in the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See also