[英]Can I subclass a abstract class which has another abstract class which is also subclassed? (C#)
可以说我想设计一个抽象系统来对文档中的部分进行计数。 我设计了两个类, Document和Section ,该文档有一个节列表和一个计算它们的方法。
public abstract class Document {
List<Section> sections;
public void addSection(Section section) {
sections.Add(section);
}
public int sectionCount() {
return sections.count;
}
}
public abstract class Section {
public string Text;
}
现在,我希望能够在多重场景中使用此代码。 例如,我有带有章节的书。 该书将是Document的子类,而Chapter将是Section的子类。 这两个类都将包含与字段计数无关的额外字段和功能。
我现在偶然发现的问题是,因为文档包含章节而不是章节,所以章节的添加功能对我来说毫无用处,因此只能将其作为章节添加到Book中。
我当时在阅读有关垂头丧气的文章,但实际上认为这不是正确的方法。 我在想也许我完全采用了错误的方法。
我的问题是这样的:我如何设计这样一个抽象系统,该系统可以被子类对象重用,这是可行的方法吗?
您需要泛型:
public abstract class Document<T> where T : Section
public abstract class Section
public class Book : Document<Chapter>
public class Chapter : Section
您可能还想让一个部分知道它可以属于哪种类型的文档。 不幸的是,这变得更加复杂:
public abstract class Document<TDocument, TSection>
where TDocument : Document<TDocument, TSection>
where TSection : Section<TDocument, TSection>
public abstract class Section<TDocument, TSection>
where TDocument : Document<TDocument, TSection>
where TSection : Section<TDocument, TSection>
public class Book : Document<Book, Chapter>
public class Chapter : Section<Book, Chapter>
我必须在协议缓冲区中执行此操作,而且比较麻烦-但是它确实允许您以强类型的方式引用这两种方式。 如果可以的话,我会选择第一个版本的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.