勇哥注:
大家好,我是微软的搬运工,今天搬一个忽略的知识点。
索引器允许类或结构的实例就像数组一样进行索引。 无需显式指定类型或实例成员,即可设置或检索索引值。 索引器类似于属性,不同之处在于它们的访问器需要使用参数。
以下示例定义了一个泛型类,其中包含用于赋值和检索值的简单 get 和 set 访问器方法。 Program
类创建了此类的一个实例,用于存储字符串。
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.
表达式主体定义
索引器的 get 或 set 访问器包含一个用于返回或设置值的语句很常见。 为了支持这种情况,表达式主体成员提供了一种经过简化的语法。 自 C# 6 起,可以表达式主体成员的形式实现只读索引器,如以下示例所示。
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
关键字。
自 C# 7.0 起,get 和 set 访问器均可作为表达式主体成员实现。 在这种情况下,必须使用 get
和 set
关键字。 例如:
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.
索引器概述
使用索引器可以用类似于数组的方式为对象建立索引。
get
取值函数返回值。set
取值函数分配值。this 关键字用于定义索引器。
value 关键字用于定义由
set
访问器分配的值。索引器不必根据整数值进行索引;由你决定如何定义特定的查找机制。
索引器可被重载。
索引器可以有多个形参,例如当访问二维数组时。
相关部分

