using System;
class IntIndexer
{
private string[] data;
public IntIndexer(int size)
{
data = new string[size];
for (int i = 0; i < size; i++) data[i] = "empty";
}
public string this[int pos]
{
get => data[pos];
set => data[pos] = value;
}
static void Main()
{
var idx = new IntIndexer(10);
idx[9] = "Some Value";
idx[3] = "Another Value";
idx[5] = "Any Value";
Console.WriteLine("\nIndexer Output\n");
for (int i = 0; i < 10; i++)
Console.WriteLine($"myInd[{i}]: {idx[i]}");
}
}
myInd[0]: empty
myInd[1]: empty
myInd[2]: empty
myInd[3]: Another Value
myInd[4]: empty
myInd[5]: Any Value
myInd[6]: empty
myInd[7]: empty
myInd[8]: empty
myInd[9]: Some Value
同一類別可定義多個索引器,參數型別/個數不同即可:
class OvrIndexer
{
private string[] data;
private int size;
public OvrIndexer(int size)
{
this.size = size;
data = new string[size];
for (int i = 0; i < size; i++) data[i] = "empty";
}
// 整數索引器
public string this[int pos]
{
get => data[pos];
set => data[pos] = value;
}
// 字串索引器:get 回傳符合值的計數,set 將所有符合值替換
public string this[string val]
{
get
{
int count = 0;
for (int i = 0; i < size; i++)
if (data[i] == val) count++;
return count.ToString();
}
set
{
for (int i = 0; i < size; i++)
if (data[i] == val) data[i] = value;
}
}
static void Main()
{
var idx = new OvrIndexer(10);
idx[9] = "Some Value";
idx[3] = "Another Value";
idx[5] = "Any Value";
idx["empty"] = "no value"; // 呼叫字串索引器 set
Console.WriteLine("\nIndexer Output\n");
for (int i = 0; i < 10; i++)
Console.WriteLine($"myInd[{i}]: {idx[i]}");
Console.WriteLine($"\nNumber of \"no value\" entries: {idx["no value"]}"); // 呼叫 get
}
}
myInd[0]: no value
myInd[1]: no value
myInd[2]: no value
myInd[3]: Another Value
myInd[4]: no value
myInd[5]: Any Value
myInd[6]: no value
myInd[7]: no value
myInd[8]: no value
myInd[9]: Some Value
Number of "no value" entries: 7
public class Matrix
{
private double[,] data = new double[10, 10];
public double this[int row, int col]
{
get => data[row, col];
set => data[row, col] = value;
}
}
呼叫:matrix[2, 3] = 5.5;
int, long...)string)索引器讓類別支援陣列語法存取內部資料,支援多載與多參數,極適合集合、矩陣、字典式查詢等場景。善用索引器可大幅提升 API 易用性。