一:索引器允許類和結構的執行個體按照與數組相同的方式進行索引,索引器類似與屬性,不同之處在於他們的訪問器採用參數。被稱為有參屬性。
如:簡單索引器執行個體:
using System;
using System.Collections.Generic;
using System.Linq; using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
IndexClass Temple = new IndexClass();
Temple[0] = "孫三";
Temple[1] = "業四";
Temple[2] = "寶五";
Console.WriteLine("冠位大爺為:{0}",Temple[0]);
Console.WriteLine("亞位大爺為:{0}", Temple[1]);
Console.WriteLine("季位大爺為 :{0}", Temple[2]);
Console.ReadLine();
}
}
class IndexClass
{
private string[] name = new string[100];
public string this[int index]
{
get {
if (index=100)
return name[0];
else
return name[index];
}
set
{
if (index < 0 || index > 100)
name[0] = value;
else
this.name[index] = value;
}
}
}
}
上例中的索引器與數組有些相似:但是索引器與數組是有區別的體現在如下:
1)索引器的索引值不受類型的限制。而用來訪問數組的索引值一琮是整數。
2)索引器允許重載,一個類可以有多個索引器。
3)索引器允許類和結構的執行個體按照與數組相同的方式進行索引,索引器類似於屬性,不同之處在於他們的訪問器採用參數,被稱為有參屬性。
4)屬性以名稱來標識,索引器以函數簽名來標識。索引器可以被重載,屬性則不可以被重載。屬性可以為靜態,索引器屬於執行個體成員,不能被聲明為static。
而且索引器可以是多參的也就是作為索引的參數可以為多個如下:
using System;
using System.Collections.Generic;
using System.Linq; using System.Text;
using System.Collections;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
ScoreIndex si = new ScoreIndex();
si["張三", 1] = 90;
si["張三", 2] = 100;
si["張三", 3] = 98;
si["李四", 1] = 94;
si["李四", 2] = 88;
si["李四", 3] = 96;
Console.WriteLine("張三的編號為1 的成績為:{0}",si["張三",1]);
Console.WriteLine("張三的所有成績為: ");
ArrayList arrTemp; arrTemp=si["張三"];
foreach (IndexClass item in arrTemp)
{
Console.WriteLine("姓名:"+item.Name+" 課程編號: "+item.CourseId+" 成績: "+item.Score+"\r\n");
}
Console.ReadLine();
}
}
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 { _name = value; }
}
public int CourseId
{
get { return _courseId; }
set { _courseId = value; }
}
public int Score
{
get { return _score; }
set { _score = value; }
}
}
class ScoreIndex
{
private ArrayList arr;
public ScoreIndex()
{
arr = new ArrayList();
}
public int this[string _name, int _courseId]
{
get
{
foreach (IndexClass item in arr)
{
if (item.Name == _name && item.CourseId == _courseId)
{
return item.Score;
}
}
return -1;
}
set
{
arr.Add(new IndexClass(_name,_courseId,value));
}
}
//重載索引器
public ArrayList this[string _name]
{
get {
ArrayList temp = new ArrayList();
foreach (IndexClass a in arr)
{
if (a.Name == _name)
{
temp.Add(a);
}
}
return temp;
}
}
}
}