C# 索引器
MSDN中对索引器的描述:
1.索引器允许类或结构的实例就像数组一样进行索引。无需显式指定类型或实例成员,即可设置或检索索引值。索引器类似于属性,不同之处在于它们的 访问需要使用参数。
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.
2. 由于在get和set访问器中包含一个用于返回和设置值的语句很常见,所以可以使用lambda表达式实现set和get访问器。下面的例子有lambda表示式实现了get访问器(只读访问器)。同时通过一个ADD函数来实现set的功能,在main程序中通过索引器可以输出arr数组中的值
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.
作者:MSDN 原文链接:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/indexers/index#BKMK_RelatedSections 2019-04-02 |