索引器 (編程)
外觀
索引器(Indexer)在面向對象程序設計中允許一個類或者結構可以如同數組一樣被索引(indexed)訪問[1]。為類定義一個索引器後,該類的行為就會像數組一樣用數組訪問運算符([ ])來訪問該類的實例。這是一種運算符重載。
C#語言中通過重定義operator[]實現了索引器。Python語言中,類如果定義了__getitem__(self, key)與__setitem__(self, key, value)方法就能實現indexer。
例子
[編輯]以下為 C#中在類中使用indexer:[2]
class OurFamily
{
public OurFamily(params string[] pMembers)
{
familyMembers = new List<string>();
familyMembers.AddRange(pMembers);
}
private List<string> familyMembers;
public string this[int index] //索引器定义的时候不带有名称,但带有 this 关键字,它指向对象实例。
{
// The get accessor
get
{
return familyMembers[index];
}
// The set accessor with
set
{
familyMembers[index] = value;
}
}
public int this[string val] //索引器(Indexer)可被重载。索引器声明的时候也可带有多个参数,参数不必须是整型。也可以是其他类型,例如字符串类型
{
// Getting index by value (first element found)
get
{
return familyMembers.FindIndex(m => m == val);
}
}
public int Length => familyMembers.Count;
}
使用:
void Main()
{
var doeFamily = new OurFamily("John", "Jane");
for (int i = 0; i < doeFamily.Length; i++)
{
var member = doeFamily[i];
var index = doeFamily[member]; // same as i in this case, but it demonstrates indexer overloading allowing to search doeFamily by value.
Console.WriteLine($"{member} is the member number {index} of the {nameof(doeFamily)}");
}
}
代碼輸出為:
John is the member number 0 of the doeFamily Jane is the member number 1 of the doeFamily
參見
[編輯]參考文獻
[編輯]- ^ jagadish980. C# - What is an indexer in C#. http://forums.sureshkumar.net/forum.php: Bulletin: SURESHKUMAR.NET FORUMS. 2008-01-29 [2011-08-01]. (原始內容存檔於September 22, 2009).
- ^ C# Interview Questions. http://www.dotnetfunda.com/: .net Funda. [2011-08-01]. (原始內容存檔於2012-03-21).