微软官方描述:索引器允许类或结构的实例就像数组一样进行索引。索引器形态类似于,不同之处在于它们的取值函数采用参数。
通俗理解:索引器(Indexer) 允许一个对象可以像数组一样被索引。当您为类定义一个索引器时,该类的行为就会像一个 虚拟数组(virtual array) 一样。您可以使用数组访问运算符([ ])来访问该类的实例。
索引的代码结构接近与类的属性定义,都是通过get和set来进行相关业务操作,只是比属性多了签名,索引允许重载,索引支持多种数据类,可以通过对象+【签名】来调用该索引
索引结构:
element-type this[int index]
{
// get 访问器
get
{
// 返回 index 指定的值
}
// set 访问器
set
{
// 设置 index 指定的值
}
}
索引简单使用:
public class Indexer {
public static int size = 10;
private string[] array = new string[size];
public Indexer() {
for (int i= 0;i < 10;i++) {
array[i] = "N/A";
}
}
/// <summary>
/// 给属性设置或获取属性值
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public string this[int i] {
get {
if (i < 0 || i >= size) {
return "";
}
else {
return array[i];
}
}
set {
if (i < 0 || i >= size) {
}
else {
array[i]=value;
}
}
}
/// <summary>
/// 查看当前属性的值是否等于传过来的值
/// </summary>
/// <param name="i"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool this[int i, string value] {
get {
if (i < 0 || i >= size) {
return false;
}
else {
if (array[i].Equals(value)) return true;
else return false;
}
}
}
}
调用:
#region Indexer
Indexer index = new Indexer();
index[0] = "Zara";
index[1] = "Riz";
index[2] = "Nuha";
index[3] = "Asif";
index[4] = "Davinder";
index[5] = "Sunil";
index[6] = "Rubic";
index[7] = "Rubic11";
index[8] = "Rubic22";
index[9] = "Rubic33";
for (int i = 0; i < Indexer.size; i++) {
Console.WriteLine(index[i]);
}
Console.WriteLine(index[1, "Riz"]);
Console.ReadKey();
#endregion
可以参考的例子:
namespace Study
{
class Program
{
static void Main(string[] args)
{
ScoreIndex s = new ScoreIndex();
s["张三", 1] = 90;
s["张三", 2] = 100;
s["张三", 3] = 80;
s["李四", 1] = 60;
s["李四", 2] = 70;
s["李四", 3] = 50;
Console.WriteLine("张三课程编号为1的成绩为:" + s["张三",1]);
Console.WriteLine("张三的所有成绩为:");
ArrayList temp;
temp = s["张三"];
foreach (IndexClass b in temp)
{
Console.WriteLine("姓名:" + b.Name + "课程编号:" + b.CourseID + "分数:" + b.Score);
}
Console.ReadKey();
}
}
class IndexClass
{
private string _name;
private int _courseid;
private int _score;
public IndexClass(string _name, int _courseid, int _score)
{
this._name = _name;
this._courseid = _courseid;
this._score = _score;
}
public string Name
{
get { return _name; }
set { this._name = value; }
}
public int CourseID
{
get { return _courseid; }
set { this._courseid = value; }
}
public int Score
{
get { return _score; }
set { this._score = value; }
}
}
class ScoreIndex
{
private ArrayList arr;
public ScoreIndex()
{
arr = new ArrayList();
}
public int this[string _name, int _courseid]
{
get
{
foreach (IndexClass a in arr)
{
if (a.Name == _name && a.CourseID == _courseid)
{
return a.Score;
}
}
return -1;
}
set
{
arr.Add(new IndexClass(_name, _courseid, value)); //arr["张三",1]=90
}
}
//重载索引器
public ArrayList this[string _name]
{
get
{
ArrayList temp = new ArrayList();
foreach (IndexClass b in arr)
{
if (b.Name == _name)
{
temp.Add(b);
}
}
return temp;
}
}
}
}