介面中的索引器(C# 編程指南) 索引器可在介面(C# 參考)上聲明。介面索引器的訪問器與類索引器的訪問器具有以下方面的不同:介面訪問器不使用修飾符。介面訪問器沒有體。因此,訪問器的用途是指示索引器是讀寫、唯讀還是唯寫。以下是介面索引器訪問器的樣本:C#複製代碼public interface ISomeInterface{ //... // Indexer declaration: stringthis[int index] { get; set; }}一個索引器的簽名必須區別於在同一介面中聲明的其他所有索引器的簽名。 樣本 下面的樣本顯示如何?介面索引器。C#複製代碼// Indexer on an interface:public interface ISomeInterface{ // Indexer declaration: intthis[int index] { get; set; }} // Implementing the interface.class IndexerClass : ISomeInterface{ privateint[] arr = newint[100]; publicintthis[int index] // indexer declaration { get { // Check the index limits. if (index < 0 || index >= 100) { return 0; } else { return arr[index]; } } set { if (!(index < 0 || index >= 100)) { arr[index] = value; } } }} class MainClass{ staticvoid Main() { IndexerClass test = new IndexerClass(); // Call the indexer to initialize the elements #2 and #5. test[2] = 4; test[5] = 32; for (int i = 0; i <= 10; i++) { System.Console.WriteLine("Element #{0} = {1}", i, test[i]); } }} 輸出 Element #0 = 0Element #1 = 0Element #2 = 4Element #3 = 0Element #4 = 0Element #5 = 32Element #6 = 0Element #7 = 0Element #8 = 0Element #9 = 0Element #10 = 0在上例中,可以通過使用介面成員的完全限定名來使用顯式介面成員實現。例如:public string ISomeInterface.this { } 但是,只有當類使用同一索引器簽名實現一個以上的介面時,為避免多義性才需要使用完全限定名。例如,如果 Employee類實現的是兩個介面 ICitizen和 IEmployee,並且這兩個介面具有相同的索引器簽名,則必須使用顯式介面成員實現。即,以下索引器聲明:public string IEmployee.this { } 在 IEmployee介面上實現索引器,而以下聲明:public string ICitizen.this { } 在 ICitizen介面上實現索引器。 (來源:msdn )