【发布时间】:2011-05-25 18:45:16
【问题描述】:
我正在尝试为实现IList 的只读集合编写一个抽象基类。这样的基类应该实现 set-indexer 以抛出 NotSupportedException,但将 get-indexer 保留为抽象。 C# 允许这种情况吗?到目前为止,这是我所拥有的:
public abstract class ReadOnlyList : IList {
public bool IsReadOnly { get { return true; } }
public object this[int index] {
get {
// there is nothing to put here! Ideally it would be left abstract.
throw new NotImplementedException();
}
set {
throw new NotSupportedException("The collection is read-only.");
}
}
// other members of IList ...
}
理想情况下,ReadOnlyList 将能够实现 setter,但保留 getter 抽象。是否有任何语法允许这样做?
【问题讨论】:
-
如果这不仅仅是一个练习,你在框架中有 ReadOnlyCollection
-
谢谢;我通常使用 ReadOnlyCollection
,尽管这种特殊情况需要 IList 的自定义实现。我确实倾向于将我的场景简化为提出问题所需的最低限度。
标签: c#