介面中的索引子 (C# 程式設計手冊)

索引子可以宣告於 interface 上。 介面索引子的存取子在下列方面與類別索引子的存取子不同:

  • 介面存取子不會使用修飾詞。
  • interface 存取子通常沒有主體。

存取子的目的是指出索引子是讀寫、唯讀還是唯寫。 您可以為 interface 中定義的索引子提供實作,但這很少見。 索引子通常會定義 API 來存取資料欄位,而且無法在 interface 中定義資料欄位。

介面索引子存取子的範例如下:

public interface ISomeInterface
{
    //...

    // Indexer declaration:
    string this[int index]
    {
        get;
        set;
    }
}

索引子的簽章必須與相同介面中所宣告之其他所有索引子的簽章不同。

範例

下列範例示範如何實作介面索引子。

// Indexer on an interface:
public interface IIndexInterface
{
    // Indexer declaration:
    int this[int index]
    {
        get;
        set;
    }
}

// Implementing the interface.
class IndexerClass : IIndexInterface
{
    private int[] arr = new int[100];
    public int this[int index]   // indexer declaration
    {
        // The arr object will throw IndexOutOfRange exception.
        get => arr[index];
        set => arr[index] = value;
    }
}
IndexerClass test = new IndexerClass();
System.Random rand = System.Random.Shared;
// Call the indexer to initialize its elements.
for (int i = 0; i < 10; i++)
{
    test[i] = rand.Next();
}
for (int i = 0; i < 10; i++)
{
    System.Console.WriteLine($"Element #{i} = {test[i]}");
}

/* Sample output:
    Element #0 = 360877544
    Element #1 = 327058047
    Element #2 = 1913480832
    Element #3 = 1519039937
    Element #4 = 601472233
    Element #5 = 323352310
    Element #6 = 1422639981
    Element #7 = 1797892494
    Element #8 = 875761049
    Element #9 = 393083859
*/

在上述範例中,您可以使用介面成員的完整名稱來使用明確介面成員實作。 例如:

string IIndexInterface.this[int index]
{
}

不過,類別實作具有相同索引子簽章的多個介面時,只需要完整名稱,即可避免模稜兩可。 例如,如果 Employee 類別實作 ICitizenIEmployee 這兩個介面,而且這兩個介面都具有相同的索引子簽章,則需要明確介面成員實作。 也就是說,下列索引子宣告:

string IEmployee.this[int index]
{
}

IEmployee 介面上實作索引子,而下列宣告:

string ICitizen.this[int index]
{
}

ICitizen 介面上實作索引子。

另請參閱