2 回答

TA貢獻(xiàn)2039條經(jīng)驗(yàn) 獲得超8個(gè)贊
C#中的有參屬性,就是索引器啊。
索引器允許類或結(jié)構(gòu)的實(shí)例就像數(shù)組一樣進(jìn)行索引。 索引器類似于 屬性,不同之處在于它們的訪問器采用參數(shù)。
索引器經(jīng)常是在主要用于封裝內(nèi)部集合或數(shù)組的類型中實(shí)現(xiàn)的。 例如,假定具有一個(gè)名為 TempRecord 的類,此類表示在 24 小時(shí)內(nèi)的 10 個(gè)不同時(shí)間記錄的華氏度。
此類包含一個(gè)表示溫度的 float 類型的名為“temps”的數(shù)組和表示記錄溫度的日期的 DateTime。
通過在此類中實(shí)現(xiàn)一個(gè)索引器,客戶端可以通過 float temp =
tr[4] 而不是 float temp = tr.temps[4] 語法訪問
TempRecord 實(shí)例中的溫度。 索引器表示法不僅簡化了客戶端應(yīng)用程序的語法,還使其他開發(fā)人員能夠更加直觀地理解類及其用途。
class TempRecord { // Array of temperature values private float [] temps = new float [10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F, 61.3F, 65.9F, 62.1F, 59.2F, 57.5F }; // To enable client code to validate input // when accessing your indexer. public int Length { get { return temps.Length; } } // Indexer declaration. // If index is out of range, the temps array will throw the exception. public float this [ int index] { get { return temps[index]; } set { temps[index] = value; } } } class MainClass { static void Main() { TempRecord tempRecord = new TempRecord(); // Use the indexer's set accessor tempRecord[3] = 58.3F; tempRecord[5] = 60.1F; // Use the indexer's get accessor for ( int i = 0; i < 10; i++) { System.Console.WriteLine( "Element #{0} = {1}" , i, tempRecord[i]); } // Keep the console window open in debug mode. System.Console.WriteLine( "Press any key to exit." ); System.Console.ReadKey(); } } /* Output: Element #0 = 56.2 Element #1 = 56.7 Element #2 = 56.5 Element #3 = 58.3 Element #4 = 58.8 Element #5 = 60.1 Element #6 = 65.9 Element #7 = 62.1 Element #8 = 59.2 Element #9 = 57.5 */ |
C# 并不將索引類型限制為整數(shù)。 例如,對索引器使用字符串可能是有用的。 通過搜索集合內(nèi)的字符串并返回相應(yīng)的值,可以實(shí)現(xiàn)此類索引器。 由于訪問器可被重載,字符串和整數(shù)版本可以共存。
在此例中,聲明了存儲(chǔ)星期幾的類。 聲明了一個(gè)
get 訪問器,它接受字符串(天名稱),并返回相應(yīng)的整數(shù)。 例如,星期日將返回 0,星期一將返回 1,等等。
// Using a string as an indexer value
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
- 2 回答
- 0 關(guān)注
- 175 瀏覽
添加回答
舉報(bào)