1. 簡(jiǎn)介:
索引器允許類(lèi)或結(jié)構(gòu)的實(shí)例就像數(shù)組一樣進(jìn)行索引入蛆。寫(xiě)法上類(lèi)似屬性。
2. 語(yǔ)法:
關(guān)鍵字符: this[]
class IndexTest
{
private int[] arrayInts = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
public int this[int index]
{
get { return arrayInts[index]; }
set { arrayInts[index] = value; }
}
}
// 使用該類(lèi)
class Program
{
static void Main(string[] args)
{
IndexTest test = new IndexTest();
Console.WriteLine(test[5]); // 6
Console.ReadKey();
}
}
3. 索引器概述:
使用索引器可以用類(lèi)似于數(shù)組的方式為對(duì)象建立索引酷含。
get
取值函數(shù)返回值鄙早。set
取值函數(shù)分配值。this
關(guān)鍵字用于定義索引器椅亚。value
關(guān)鍵字用于定義由set
索引器分配的值限番。索引器不必根據(jù)整數(shù)值進(jìn)行索引;由你決定如何定義特定的查找機(jī)制呀舔。
索引器可被重載弥虐。
索引器可以有多個(gè)形參,例如當(dāng)訪問(wèn)二維數(shù)組時(shí)别威。
4. 索引器其他用法:
1> 索引器可以有多個(gè)形參躯舔,例如多維數(shù)組的用法。
public int this[int index, int index2]
{
get
{
if (index >= arrayInts.Length)
{
throw new Exception("索引超出了界線");
}
else
{
return arrayInts[index];
}
}
set { arrayInts[index] = value; }
}
// 調(diào)用:
static void Main(string[] args)
{
IndexTest test = new IndexTest();
Console.WriteLine(test[12,6]);
Console.ReadKey();
}
2> C# 并不將索引類(lèi)型限制為整數(shù)省古。 例如粥庄,對(duì)索引器使用字符串可能是有用的。 通過(guò)搜索集合內(nèi)的字符串并返回相應(yīng)的值豺妓,可以實(shí)現(xiàn)此類(lèi)索引器惜互。
案例說(shuō)明:在此例中,聲明了存儲(chǔ)星期幾的類(lèi)琳拭。 聲明了一個(gè) get 訪問(wèn)器训堆,它接受字符串(天名稱),并返回相應(yīng)的整數(shù)白嘁。 例如坑鱼,星期日將返回 0,星期一將返回 1絮缅,等等鲁沥。
class DayCollection
{
string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
// This method finds the day or returns -1
private int GetDay(string testDay)
{
for (int j = 0; j < days.Length; j++)
{
if (days[j] == testDay)
{
return j;
}
}
throw new System.ArgumentOutOfRangeException(testDay, "testDay must be in the form \"Sun\", \"Mon\", etc");
}
// The get accessor returns an integer for a given string
public int this[string day]
{
get
{
return (GetDay(day));
}
}
}
class Program
{
static void Main(string[] args)
{
DayCollection week = new DayCollection();
System.Console.WriteLine(week["Fri"]);
// Raises ArgumentOutOfRangeException
System.Console.WriteLine(week["Made-up Day"]);
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
// Output: 5
// Output: 5
泛型類(lèi)跟索引器
//A繼承自Program,并且泛型T耕魄,需要是一個(gè)引用類(lèi)型画恰,并且泛型類(lèi),需要遵守IComparable接口
class A<T> : Program where T : class, IComparable<T>
{
private T[] list;
public T this[int index]
{
get
{
return list[index];
}
set
{
list[index] = value;
}
}
}