索引器 (编程)

索引器（Indexer）是一种运算符重载。在面向对象程序设计中允许一个类或者结构如同数组一样被索引（indexed）访问。在为类定义一个索引器后，该类的行为便會如同数组一样，通過数组访问运算符（[ ]）来访问该类的实例。

在C♯语言中是通过重定义operator[]來实现索引器。而在Python语言中，类如果定义了__getitem__(self, key)与__setitem__(self, key, value)方法便能实现indexer。

 例子

 在C#語言的類中使用indexer 
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

 参见 
 变异子与访问子

 参考文献

Category:面向对象的程序设计
Category:运算符_(编程)