[英]polymorphism, generics and anonymous types 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被聲明為另一個類的屬性,我無法使它工作。
如果需要,我可以提供更多細節。 謝謝你們的支持。
這個課程無效:
public class Body
{
public Items<T> Items {get;set;}
}
您需要在此處定義具體類型,或者也使Body
成為泛型類型。 所以要么:
public class Body<T>
{
public Items<T> Items {get;set;}
}
要么:
public class Body
{
public Items<MyClass> Items {get;set;}
}
為Items創建一個接口
public interface IItems: IEnumerable, IEnumerator{
}
public class Items<T>: IItems
{
// Do all the plumbing for creating an enumerable collection
}
然后在其他地方使用它。
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;}
}
最明顯的選擇是聲明你的類型對象列表,但是你必須處理拳擊和取消裝箱對象的性能損失。 我想我會創建一個界面來定義你要從項目中尋找的行為,並確保每個項目實現該界面。
public IMyInterface
{
string dosomething();
}
public Items<IMyInterface> Items {get;set;}
然后,當您迭代它們時,您可以要求每個項目執行一些有用的操作。
這可能對你有用:
public class Document<T> where T: IEnumerable, IEnumerator
{
private Section<T>[] Sections{get;set;}
}
private class Section<T>
{
private Body<T> body {get;set;}
}
private class Body<T>
{
private Items<T> Items {get;set;}
}
private class Items<T>:IEnumerable, IEnumerator
{
// Do all the plumbing for creating an enumerable collection
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}
/* Needed since Implementing IEnumerator*/
public bool MoveNext()
{
return false;
}
public void Reset()
{
}
public object Current
{
get{ return new object();}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.