【发布时间】:2015-06-16 16:21:35
【问题描述】:
我有一个抽象类DataBase,它用作不同类型数据的基类,例如简单值类型(byte、int、string 等)和更复杂的数据结构,例如@ 987654326@ 和DataDictionary。 DataList 实现IList<DataBase>,DataDictionary 实现IDictionary<string, DataBase>。
为了简单起见,我继续在 DataBase 类中添加了一些我经常使用的东西,因此不需要强制转换:
public virtual DataBase this[string name] {
get { throw new NotSuppportedException(); }
set { throw new NotSuppportedException(); }
}
public virtual DataBase this[int index] { ...
// Example usage:
var someData = rootData["SomeList"][10];
这些方法随后在基类中被覆盖。或者不是,在这种情况下,它在使用时会引发异常。为了让事情变得更简单,我还想以类似的方式实现IEnumerable<DataBase>:
public virtual IEnumerator<DataBase> GetEnumerator() {
throw new NotSuppportedException();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return GetEnumerator();
}
但由于 DataDictionary 是一个 IDictionary,因此是 IEnumerable<KeyValuePair<string, DataBase>>,我遇到了无法覆盖 DataBase 的 GetEnumerator() 的问题。我尝试了许多不同的方法:
(public|protected) (override) IEnumerator<DataBase> DataBase.GetEnumerator()
(public|protected) (override) IEnumerator<DataBase> IEnumerable<DataBase>.GetEnumerator()
修饰符“覆盖”对此项无效 (CS0106)
现在,我不知道该寻找什么来解决这个问题 - 这叫什么? - 或者哪个限制(如果有的话)阻止我做我想做的事情以及为什么它可能存在。
相关问答"C# overriding an interface contract method of a base class"没有解决问题。如果您要将x 的类型更改为TestBase,代码会输出“Base”。
【问题讨论】:
标签: c# inheritance overriding