Mou*_*him 5 c# generics polymorphism
请考虑以下情形.
文档 - >部分 - >正文 - >项目
文档有部分,一个部分包含一个正文.正文包含一些文本和项目列表.这些项目就是问题所在.有时这些项是字符串的基本列表,但有时这些项包含自定义数据类型的列表.
所以:
public class Document
{
public Section[] Sections{get;set;}
}
public class Section
{
public SectionType Type{get;set;}
public Body {get;set;}
}
public class Body
{
//I want the items to be depending on the section type.
//If e.g. the sectiontype is experience, I want the Items to be created with type //Experience. If sectiontype is default I want the Items to be created with type string
public Items<T> Items {get;set;}
}
public class Items<T>:IEnumerable, IEnumerator
{
// Do all the plumbing for creating an enumerable collection
}
public class Experience
{
public string Prop1{get;set;}
public string Prop2 {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
我无法让这个工作.属性Items必须由类型定义才能进行编译.我被困在这里.我可以通过为我使用的每种部分创建一个Section类来轻松解决这个问题.但问题是所有其他代码都是相同的,并且该部分的所有操作都是相同的.唯一不同的是Body中使用的列表类型.
这是什么最好的做法.我已经尝试过泛型,抽象等.如果直接从调用程序创建Items类,我可以使它工作,但是如果Items被声明为另一个类的属性,我无法使它工作.
如果需要,我可以提供更多细节.谢谢你们的支持.
为 Item 制作一个接口
public interface IItems: IEnumerable, IEnumerator{
}
public class Items<T>: IItems
{
// Do all the plumbing for creating an enumerable collection
}
Run Code Online (Sandbox Code Playgroud)
然后在其他地方使用它。
public class Body
{
//I want the items to be depending on the section type.
//If e.g. the sectiontype is experience, I want the Items to be created with type //Experience. If sectiontype is default I want the Items to be created with type string
public IItems Items {get;set;}
}
Run Code Online (Sandbox Code Playgroud)