C# 索引器(Indexer) this關鍵字的作用
阿新 • • 發佈:2018-12-07
索引器使你可從語法上方便地建立類、結構或介面,以便客戶端應用程式能像訪問陣列一樣訪問它們。 在主要目標是封裝內部集合或陣列的型別中,常常要實現索引器。
話不多說,直接上程式碼
//現在要建立一個類,People,我想像用陣列一樣建立它People[]。 class People { public string name; public int age; public People(string name,int age) { this.name = name; this.age = age; } //以下是索引器的程式碼 public People this[int i] { get { return this[i]; } set { this[i] = value; } } //也可以這樣寫 //public People this[int i] //{ // get => this[i]; // set => this[i] = value; //} }
class Program { static void Main(string[] args) { People[] peoples = new People[10]; peoples[0] = new People("Link", 18); peoples[1] = new People("Zelda", 118); Console.WriteLine($"Name:{peoples[0].name},Age:{peoples[0].age}"); Console.WriteLine($"Name:{peoples[1].name},Age:{peoples[1].age}"); Console.ReadKey(); } }
最後輸出結果:
Name:Link,Age:18
Name:Zelda,Age:118
我剛才舉的例子在實際中並不常始用,反倒是這樣的情況比較多。我現在有一個類叫做名冊,裡面有string[] names存著不同學生的名字,現在要獲取這個類的物件的string[] names陣列中的這些名字,我通常是這樣的mingce.names[i] 來獲取。其實這裡使用索引器就很好,可以mingce[i]這樣來獲取。
一個例子
class Mingce { public string[] names = new string[3] { "牧之原翔子", "櫻島麻衣", "雙葉理央" }; public int Length { get { return names.Length; } } public string this[int i]=>names[i]; //宣告索引器 } class Program { static void Main(string[] args) { Mingce mingce = new Mingce(); Console.WriteLine($"名字:{mingce[0]}"); Console.WriteLine($"名字:{mingce[1]}"); Console.WriteLine($"名字:{mingce[2]}"); Console.WriteLine($"名字:{mingce.names[0]}"); Console.WriteLine($"名字:{mingce.names[1]}"); Console.WriteLine($"名字:{mingce.names[2]}"); Console.ReadKey(); } }
除了可以以int值作為索引外,還可以是string的型別。並且可以this[int i , int j]這樣構建二維陣列。具體可以自己嘗試。
參考資料:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/indexers/index