你需要仿制药:
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>
我必须在协议缓冲区中这样做,这很混乱——但它允许您以强类型的方式引用这两种方式。如果你能逃脱的话,我会选第一版的。