如何将索引器行为定义到接口中?

35

是否可以从接口中添加索引器行为?

像这样:

interface IIndexable<T>
{
   T this[string index];
}
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
一个更通用的界面(来自
interface IIndexable<TKey, TValue>
{
    TValue this[TKey key] { get; set; }
}

我只是想知道为什么他们没有将它包含在mscorlib中,这样IDictionary就可以实现它了。这本应是有意义的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接