跳转到内容

索引器 (编程)

维基百科,自由的百科全书

索引器(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

参见

[编辑]

参考文献

[编辑]
  1. ^ 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). 
  2. ^ C# Interview Questions. http://www.dotnetfunda.com/: .net Funda. [2011-08-01]. (原始内容存档于2012-03-21).