是否可以从接口中添加索引器行为?
像这样:
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# 参考)。 接口索引器的访问器与类索引器的访问器有以下不同之处:
- 接口访问器不使用修饰符。
- 接口访问器没有主体。
interface IIndexable<TKey, TValue>
{
TValue this[TKey key] { get; set; }
}
我只是想知道为什么他们没有将它包含在mscorlib中,这样IDictionary就可以实现它了。这本应是有意义的。