如何在 C# 中過載 [] 運算子?
[]運算子被稱為索引器。
索引器允許物件被編入索引,如同陣列。當你為一個類定義索引器時,這個類表現得類似於一個虛擬陣列。然後你可以使用陣列訪問運算子 ([ ]) 來訪問這個類的例項。
索引器可以被過載。索引器還可以用多個引數宣告,每個引數都可以是不同型別。索引不一定必須是整數。
示例 1
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
示例 2
覆蓋 []
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP