前言:
索引器(Indexer)可以像操作數組一樣來訪問對象的元素。它允許你使用索引來訪問對象中的元素,就像使用數組索引一樣。在C#中,索引器的定義方式類似于屬性,但具有類似數組的訪問方式。
索引器:
public returnType this[indexType index] {// 索引器的 get 訪問器get {// 返回與索引相關的值}// 索引器的 set 訪問器set {// 設置與索引相關的值}
}
returnType
是索引器返回的值的類型。indexType
是索引的類型。this[index]
是索引器的聲明,其中index
是索引參數。get
訪問器用于獲取與指定索引相關的值。set
訪問器用于設置與指定索引相關的值。
假設有一個名為MyCollection
的類,可以通過類似myCollection[0]
的方式來訪問其中的元素。這時候就可以使用索引器。在MyCollection
類中定義一個索引器,可以使用整數索引來訪問其中的元素。代碼中體會更容易理解
創建一個項目,創建一個MyCollection類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace 索引器
{internal class MyCollection{private string[] elements = new string[3] { "1","2","3"}; // 創建1~3字符串的數組// 索引器定義public string this[int index]{get{// 在獲取元素時,返回對應索引的元素return elements[index];}set{// 在設置元素時,將值賦給對應索引的元素elements[index] = value;}}}
}
program類:
namespace 索引器
{internal class Program{static void Main(string[] args){MyCollection collection = new MyCollection();// 修改第一個元素的值collection[0] = "Element 1";// 獲取第一、二個元素的值string element1 = collection[0];string element2 = collection[1];// 打印第一、二個元素的值Console.WriteLine("第一個元素的值是:" + element1);Console.WriteLine("第二個元素的值是:" + element2);}}
?結果: