如何定义接口的索引器行为?

问题描述 投票:0回答:3

是否可以从界面添加索引器行为?

类似这样的:

interface IIndexable<T>
{
   T this[string index];
}
c# interface
3个回答
49
投票

是的,这是可能的。事实上,您所缺少的只是索引器上的 getter/setter。只需添加如下:

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

15
投票

来自MSDN

public interface ISomeInterface
{
    // ...

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

索引器可以在接口上声明(C# 参考)。的访问器 接口索引器与类索引器的访问器的不同之处在于 以下方式:

  • 接口访问器不使用修饰符。
  • 接口访问器没有主体。

3
投票

更通用的界面(取自

IDictionary<,>
),将是:

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

我只是想知道为什么他们不将其包含在 mscorlib 中,以便 IDictionary 可以实现它。这是有道理的。

© www.soinside.com 2019 - 2024. All rights reserved.