考慮這種情況。從列表中的多個通用類型檢索值[這是甚至可能的]
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]在編譯時是不知道的。如果在抽象中有意義,可以將TableItems屬性提取到Baseclass(DocumentBase)中。 – chrsi
我不能這樣做,因爲TableItem依賴於傳遞給Document類的泛型。 –
你需要用'TableItems'來做什麼?在編譯時你不會知道類型,那麼你可以用它做什麼? –