【发布时间】:2012-03-24 02:29:55
【问题描述】:
是否可以从界面添加索引器行为?
类似这样的:
interface IIndexable<T>
{
T this[string index];
}
【问题讨论】:
是否可以从界面添加索引器行为?
类似这样的:
interface IIndexable<T>
{
T this[string index];
}
【问题讨论】:
一个更通用的接口(取自IDictionary<,>)是:
interface IIndexable<TKey, TValue>
{
TValue this[TKey key] { get; set; }
}
我只是想知道为什么他们没有将它包含在 mscorlib 中,以便 IDictionary 可以实现它。这是有道理的。
【讨论】:
是的,这是可能的。事实上,您所缺少的只是索引器上的 getter/setter。只需添加如下:
interface IIndexable<T>
{
T this[string index] {get; set;}
}
【讨论】:
来自MSDN:
public interface ISomeInterface
{
//...
// Indexer declaration:
string this[int index]
{
get;
set;
}
}
可以在接口上声明索引器(C# 参考)。的访问者 接口索引器与类索引器的访问器不同 以下方式:
- 接口访问器不使用修饰符。
- 接口访问器没有主体。
【讨论】: