請考慮以下情形。多態,泛型和匿名類型C#
文件 - >組 - >車身 - >產品
文件具有部分,一個部分包含一個機構。一個正文有一些文本和一個項目列表。這些項目就是問題所在。有時項目是一個基本的字符串列表,但有時這些項目包含一個自定義數據類型的列表。
所以:
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必須由一個類型定義才能編譯。我被困在這裏。我可以通過爲每一種我使用的節創建一個Section類來解決這個問題。但問題是所有其他代碼都是相同的,並且該部分上的所有操作都是相同的。唯一不同的是Body中使用的列表類型。
這是什麼最佳實踐。我已經嘗試過泛型,抽象等。如果直接從調用程序創建Items類,我可以使其工作,但如果Items被聲明爲另一個類的屬性,則無法使其工作。
我可以根據需要提供更多細節。謝謝你們和女孩們的支持。
的稱號也許提的匿名類型也沒用這裏... – digEmAll 2011-02-03 17:17:17
如果sectionType是在科類的屬性,什麼樣的影響不會改變這對身體中的物品?你需要重新創建它們嗎?我認爲你應該使節類通用。 – Kell 2011-02-03 17:17:42
是不是有一個原因,你不是簡單地做一個Item抽象類,然後像StringItem和任何其他你需要的自定義Item類型,然後將你的Items屬性表示爲List- ?對我來說,這似乎是一種自然的方式來表示你描述的結構。 –
SpaceghostAli
2011-02-03 17:19:25