C#的索引器允許我們對一個實例像數組一樣進行索引。當我們在一個類中定義了索引器之后,我們可以通過數組操作符([ ])像操作數組一樣來訪問這個類的實例。
- 索引器的好處就是簡化的數組和集合成員的存取操作。
- 索引器可被重載。
- 索引器可以有多個形參,例如當訪問二維數組時。
syntax -- from MSDN
public int this[int index] // Indexer declaration
{
// get and set accessors
}
例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class Student
{
public int Number { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
}
class IndexerExample
{
private IList<Student> students = new List<Student>();
public IndexerExample()
{
students.Add(new Student
{
Number = 1,
Name = "Jason",
Sex = "Male"
});
students.Add(new Student
{
Number = 2,
Name = "Maggie",
Sex = "Female"
});
students.Add(new Student
{
Number = 3,
Name = "Lucy",
Sex = "Female "
});
}
public Student getStudent(string name)
{
foreach (Student student in students)
{
if (student.Name == name)
{
return student;
}
}
return null;
}
public Student getStudent(int num)
{
foreach (Student student in students)
{
if (student.Number == num)
{
return student;
}
}
return null;
}
//define indexer
public Student this[int num]
{
get
{
foreach (Student student in students)
{
if (student.Number == num)
{
return student;
}
}
return null;
}
}
// overload indexer
public Student this[string name]
{
get
{
foreach (Student student in students)
{
if (student.Name == name)
{
return student;
}
}
return null;
}
}
}
class Program
{
static void Main(string[] args)
{
IndexerExample myStudents = new IndexerExample();
Console.WriteLine(myStudents.getStudent(1).Sex);
Console.WriteLine(myStudents[1].Sex);
Console.WriteLine(myStudents.getStudent("Maggie").Sex);
Console.WriteLine(myStudents["Maggie"].Sex);
Console.ReadLine();
}
}
}
// Output
// "Male"
// "Male"
// "Female"
// "Female"