在C#中,自定義索引(Custom Indexers)是指允許對(duì)象像數(shù)組一樣,通過索引訪問其中的元素。自定義索引器為類、結(jié)構(gòu)或接口提供了類似數(shù)組的語法,但其行為和存儲(chǔ)方式可以根據(jù)需要自定義。
自定義索引器的定義
索引器的定義類似于屬性(Property),但使用 this 關(guān)鍵字來定義,并且接受一個(gè)或多個(gè)參數(shù)來表示索引。其語法如下:
public class MyClass
{
private Dictionary<int, string> _data = new Dictionary<int, string>();
public string this[int index]
{
get
{
if (_data.ContainsKey(index))
{
return _data[index];
}
else
{
return "Index out of range";
}
}
set
{
_data[index] = value;
}
}
}
使用索引器
定義了索引器后,就可以像訪問數(shù)組那樣來訪問對(duì)象的元素了
MyClass myObject = new MyClass();
myObject[0] = "Hello";
myObject[1] = "World";
Console.WriteLine(myObject[0]); // 輸出 "Hello"
Console.WriteLine(myObject[1]); // 輸出 "World"
多參數(shù)索引器
索引器不僅可以接受一個(gè)參數(shù),還可以接受多個(gè)參數(shù)
public class Matrix
{
private int[,] _matrix = new int[10, 10];
public int this[int row, int col]
{
get { return _matrix[row, col]; }
set { _matrix[row, col] = value; }
}
}
使用時(shí),可以傳入兩個(gè)參數(shù)來訪問矩陣的元素:
Matrix matrix = new Matrix();
matrix[0, 0] = 1;
matrix[1, 2] = 5;
Console.WriteLine(matrix[0, 0]); // 輸出 "1"
Console.WriteLine(matrix[1, 2]); // 輸出 "5"
-
訪問修飾符:索引器可以有
get和set訪問器,也可以選擇性地實(shí)現(xiàn)只讀或只寫索引器。 - 索引類型:索引器的參數(shù)可以是任意類型,不一定是整數(shù)。你可以定義字符串、枚舉或其他類型的索引。
- 多個(gè)索引器:同一個(gè)類可以定義多個(gè)索引器,但它們的參數(shù)列表必須不同(即必須有不同的簽名)。
索引器非常適合用于類內(nèi)部表示數(shù)據(jù)集合的情況,例如數(shù)組、列表或字典。在這些情況下,索引器使得代碼更加簡(jiǎn)潔和直觀。