[] 運算子被稱為索引器。
索引器允許對物件進行索引,例如陣列。當您為一個類別定義一個索引器時,該類別的行為類似於一個虛擬數組。然後,您可以使用陣列存取運算子([ ])存取該類別的實例。
索引器可以被重載。索引器也可以聲明多個參數,並且每個參數可以是不同的類型。索引不一定必須是整數。
static void Main(string[] args){ IndexerClass Team = new IndexerClass(); Team[0] = "A"; Team[1] = "B"; Team[2] = "C"; Team[3] = "D"; Team[4] = "E"; Team[5] = "F"; Team[6] = "G"; Team[7] = "H"; Team[8] = "I"; Team[9] = "J"; for (int i = 0; i < 10; i++){ Console.WriteLine(Team[i]); } Console.ReadLine(); } class IndexerClass{ private string[] names = new string[10]; public string this[int i]{ get{ return names[i]; } set { names[i] = value; } } }
A B C D E F G H I J
static class Program{ static void Main(string[] args){ IndexerClass Team = new IndexerClass(); Team[0] = "A"; Team[1] = "B"; Team[2] = "C"; for (int i = 0; i < 10; i++){ Console.WriteLine(Team[i]); } System.Console.WriteLine(Team["C"]); Console.ReadLine(); } } class IndexerClass{ private string[] names = new string[10]; public string this[int i]{ get{ return names[i]; } set{ names[i] = value; } } public string this[string i]{ get{ return names.Where(x => x == i).FirstOrDefault(); } } }
A B C C
以上是如何重載 C# 中的運算子?的詳細內容。更多資訊請關注PHP中文網其他相關文章!