2017-07-26 15 views
0

考慮這種情況。從列表中的多個通用類型檢索值[這是甚至可能的]

public abstract class DocumentBase 
    { 
     public int Index { get; set; } 
    } 

    public class Document<T> : DocumentBase where T : class 
    { 
     //Items which are to be inserted into a table on the document 
     private List<T> TableItems; 

     public Document(int index, List<T> tableItems) 
     { 
      Index = index; 
      TableItems = tableItems; 
     } 
    } 

我然後創建文檔基的名單,但填充類型,以與一般是在每個項目不同的「文件」列表中。

 var documents = new List<DocumentBase>(); 

     var documentContentsType1 = new List<DocumentContentType1> { new DocumentContentType1("docInfo1") }; 
     var documentContentsType2 = new List<DocumentContentType2> { new DocumentContentType2("docInfo2") }; 

     var documentType1 = new Document<DocumentContentType1>(1, documentContentsType1); 
     var documentType2 = new Document<DocumentContentType2>(2, documentContentsType2); 

     documents.Add(documentType1); 
     documents.Add(documentType2); 

所以我在文檔庫列表中添加了兩種不同的文檔類型。

我現在想訪問每個列表的Document類的屬性。所以像這樣的例子,documents[0].TableItems

我只能從DocumentsBase訪問屬性,可以理解。

我可以在我的設置中更改什麼來解決此問題?

+0

你試圖從一個派生類訪問屬性。這是行不通的,因爲實際的文檔類[0]在編譯時是不知道的。如果在抽象中有意義,可以將TableItems屬性提取到Baseclass(DocumentBase)中。 – chrsi

+0

我不能這樣做,因爲TableItem依賴於傳遞給Document類的泛型。 –

+0

你需要用'TableItems'來做什麼?在編譯時你不會知道類型,那麼你可以用它做什麼? –

回答

2

您可以在DocumentBase中聲明抽象方法,然後在子類中重寫它,因此它返回一些關於對象的信息(它會是一種getter)。我想不出任何其他的方式。

+0

這不起作用,因爲我無法將TableItems轉換爲動態列表。直到運行時它纔會意識到它是一個列表。 –

0

有一些概率可能會增加一個從DocumentBase繼承的類的對象,但不是Document類型的對象。

你可以做的是:

documents.OfType<Document<DocumentBaseType>>().ToList()[0].TableItems 

public abstract class DocumentBaseType{} 

,讓你DocumentType1和DocumentType2延長DocumentBaseType

+0

我想使它通用,所以我將無法指定類型。 –

相關問題