簡體   English   中英

如何為接口定義索引器行為?

[英]How to define Indexer behaviour to an Interface?

是否可以從接口添加索引器行為?

這樣的事情:

interface IIndexable<T>
{
   T this[string index];
}

對的,這是可能的。 事實上,你所缺少的只是索引器上的getter / setter。 只需添加如下:

interface IIndexable<T>
{
     T this[string index] {get; set;}
}

來自MSDN

public interface ISomeInterface
{
    //...

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

索引器可以在接口上聲明(C#Reference)。 接口索引器的訪問器在以下方面與類索引器的訪問器不同:

  • 接口訪問器不使用修飾符。
  • 接口訪問器沒有正文。

更通用的接口(取自IDictionary<,> )將是:

interface IIndexable<TKey, TValue>
{
    TValue this[TKey key] { get; set; }
}

我只是想知道為什么他們沒有將它包含在mscorlib中,所以IDictionary可以實現它。 這是有道理的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM