索引器與數組的比較:
索引器的索引值不受類型限制。用來訪問數組的索引值一定是整數,而索引器可以是其他類型的索引值。
索引器允許重載,一個類可以有多個索引器。
索引器不是一個變量沒有直接對應的數據存儲地方。索引器有get和set訪問器。
索引器允許類和結構的實例按照與數組相同的方式進行索引,索引器類似與屬性,不同之處在於他們的訪問器採用參數。被稱爲有參屬性。
簡單的索引器實例:
索引器與屬性的比較:
標示方式:屬性以名稱來標識,索引器以函數簽名來標識。
索引器可以被重載。屬性則不可以被重載。
屬性可以爲靜態的,索引器屬於實例成員,不能被聲明爲static
多參數索引器實例:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
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;
}
}
}
}
備註:
所有索引器都使用this關鍵詞來取代方法名。Class或Struct只允許定義一個索引器,而且總是命名爲this。
索引器允許類或結構的實例按照與數組相同的方式進行索引。索引器類似於屬性,不同之處在於它們的訪問器採用參數。
get 訪問器返回值。set 訪問器分配值。
this 關鍵字用於定義索引器。
value 關鍵字用於定義由 set 索引器分配的值。
索引器不必根據整數值進行索引,由您決定如何定義特定的查找機制。
索引器可被重載。
索引器可以有多個形參,例如當訪問二維數組時。
索引器可以使用百數值下標,而數組只能使用整數下標:如下列定義一個String下標的索引器
public int this [string name] {...}
屬性和索引器
屬性和索引器之間有好些差別:
類的每一個屬性都必須擁有唯一的名稱,而類裏定義的每一個索引器都必須擁有唯一的簽名(signature)或者參數列表(這樣就可以實現索引器重載)。
屬性可以是static(靜態的)而索引器則必須是實例成員。
摘自紅色黑客聯盟(www.7747.net) 原文:http://www.7747.net/kf/201010/76539.html