1. 概述
索引器允許類或結構的執行個體就像數組一樣進行索引。索引器類似於屬性,不同之處在於它們的訪問器採用參數。索引器在文法上方便您建立用戶端應用程式可將其作為數組訪問的類、結構或介面。索引器經常是在主要用於封裝內部集合或數組的類型中實現的。
例如,假定具有一個名為 TempRecord 的類,此類表示在 24 小時內的 10 個不同時間記錄的華氏度。此類包含一個表示溫度的 float 類型的名為“temps”的數組和表示記錄溫度的日期的 DateTime。通過在此類中實現一個索引器,用戶端可以通過 float temp = tr[4] 而不是 float temp = tr.temps[4] 文法訪問 TempRecord 執行個體中的溫度。索引器標記法不僅簡化了用戶端應用程式的文法,還使其他開發人員能夠更加直觀地理解類及其用途。使用索引器可以用類似於數組的方式為對象建立索引。
get 訪問器傳回值。set 訪問器分配值。this 關鍵字用於定義索引器。value 關鍵字用於定義由 set 索引器分配的值。
索引器不必根據整數值進行索引,由您決定如何定義特定的尋找機制。索引器可被重載索引器可以有多個形參,例如當訪問二維數組時。
2. 樣本:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NetTest
{
public class TestIndexClass
{
public void Test()
{
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++)
{
// This example validates the input on the client side. You may
// choose to validate it in the class that implements the indexer, and throw an
// exception or return an error code in the case of invalid input.
if (i < tempRecord.Length)
{
System.Console.WriteLine("Element #{0} = {1}", i, tempRecord[i]);
}
else
{
System.Console.WriteLine("Index value of {0} is out of range", i);
}
}
//Uncomment this code to see how the .NET Framework handles indexer exceptions
//try
//{
// System.Console.WriteLine("Element #{0} = {1}", tempRecord[tempRecord.Length]);
//}
//catch (System.ArgumentOutOfRangeException e)
//{
// System.Console.WriteLine(e);
//}
DayCollection week = new DayCollection();
System.Console.WriteLine(week["Fri"]);
System.Console.WriteLine(week["Made-up Day"]);
}
}
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 };
// Auto-Implemented Property
System.DateTime date { get; set; }
// To enable client code to validate input
// when accessing your indexer.
public int Length
{
get { return temps.Length; }
}
// Indexer declaration.
// Input parameter is validated by client
// code before being passed to the indexer.
public float this[int index]
{
get
{
return temps[index];
}
set
{
temps[index] = value;
}
}
}
//C# 並不將索引類型限制為整數。例如,對索引器使用字串可能是有用的。通過搜尋集合內的字串並返回相應的值,可以實現此類索引器。
//由於訪問器可被重載,字串和整數版本可以共存。
class DayCollection
{
string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
// This method finds the day or returns -1
private int GetDay(string testDay)
{
int i = 0;
foreach (string day in days)
{
if (day == testDay)
{
return i;
}
i++;
}
return -1;
}
// The get accessor returns an integer for a given string
public int this[string day]
{
get
{
return (GetDay(day));
}
}
}
}