如何为接口定义索引器行为?
是否可以从接口添加索引器行为?
像这样的东西:
interface IIndexable { T this[string index]; }
对的,这是可能的。 事实上,你所缺少的只是索引器上的getter / setter。 只需添加如下:
interface IIndexable { T this[string index] {get; set;} }
来自MSDN :
public interface ISomeInterface { //... // Indexer declaration: string this[int index] { get; set; } }
索引器可以在接口上声明(C#Reference)。 接口索引器的访问器在以下方面与类索引器的访问器不同:
- 接口访问器不使用修饰符。
- 接口访问器没有正文。
更通用的接口(取自IDictionary<,>
)将是:
interface IIndexable { TValue this[TKey key] { get; set; } }
我只是想知道为什么他们没有将它包含在mscorlib中,所以IDictionary可以实现它。 这是有道理的。