考虑以下场景。
文档 -> 部分 -> 正文 -> 项目
文档有部分,部分包含正文。正文有一些文本和项目列表。这些项目就是问题的内容。有时项目是基本的字符串列表,但有时项目包含自定义数据类型的列表。
So:
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;}
}
我无法让这个工作。属性 Items 必须由类型定义才能进行编译。我被困在这里了。我可以通过为我使用的每种部分创建一个部分类来轻松解决此问题。但问题是所有其他代码都是相同的,并且该部分上的所有操作都是相同的。唯一不同的是正文中使用的列表类型。
对此的最佳实践是什么。我尝试过泛型、抽象等。如果直接从调用程序创建 Items 类,我可以让它工作,但如果 Items 被声明为另一个类的属性,我就无法让它工作。
如果需要,我可以提供更多详细信息。谢谢你们的支持。
该类无效:
public class Body
{
public Items<T> Items {get;set;}
}
您需要在这里定义一个具体类型或 makeBody
也是泛型类型。所以要么:
public class Body<T>
{
public Items<T> Items {get;set;}
}
or:
public class Body
{
public Items<MyClass> Items {get;set;}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)