如何定义接口的索引器行为
本文关键字:索引 接口 何定义 定义 | 更新日期: 2023-09-27 18:26:49
是否可以从接口添加索引器行为?
像这样的东西:
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#引用)上声明。的访问者接口索引器不同于以下方式:
- 接口访问器不使用修饰符
- 接口访问器没有正文
一个更通用的接口(取自IDictionary<,>
)将是:
interface IIndexable<TKey, TValue>
{
TValue this[TKey key] { get; set; }
}
我只是想知道他们为什么不把它包含在mscorlib中,这样IDictionary就可以实现它。这是有道理的。