我正在尝试为实现的只读集合编写一个抽象基类IList
.这样的基类应该实现set-indexer来抛出a NotSupportedException
,但是将get-indexer保留为abstract.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 ...
}
Run Code Online (Sandbox Code Playgroud)
理想情况下ReadOnlyList
,能够实现setter,但保留getter摘要.有没有允许这个的语法?
将工作委派给受保护的成员,然后根据所需的行为将其标记为抽象或虚拟.尝试这样的事情:
// implementor MUST override
protected abstract object IndexerGet(int index);
// implementor can override if he wants..
protected virtual void IndexerSet(int index, object value)
{
throw new NotSupportedException("The collection is read-only.");
}
public object this[int index] {
get {
return IndexerGet(index);
}
set {
IndexerSet(index, value);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1522 次 |
最近记录: |