简体   繁体   English

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

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

Is it possible to add the indexer behaviour from an interface? 是否可以从接口添加索引器行为?

something like this : 这样的事情:

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

Yes, it is possible. 对的,这是可能的。 In fact, all you're missing is the getter/setter on your indexer. 事实上,你所缺少的只是索引器上的getter / setter。 Just add it as follows: 只需添加如下:

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

From MSDN : 来自MSDN

public interface ISomeInterface
{
    //...

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

Indexers can be declared on an interface (C# Reference). 索引器可以在接口上声明(C#Reference)。 Accessors of interface indexers differ from the accessors of class indexers in the following ways: 接口索引器的访问器在以下方面与类索引器的访问器不同:

  • Interface accessors do not use modifiers. 接口访问器不使用修饰符。
  • An interface accessor does not have a body. 接口访问器没有正文。

A bit more generic interface (taken from IDictionary<,> ), would be: 更通用的接口(取自IDictionary<,> )将是:

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

I only wonder why they didn't include it in mscorlib, so that IDictionary could implement it. 我只是想知道为什么他们没有将它包含在mscorlib中,所以IDictionary可以实现它。 It would've made sense. 这是有道理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM