2013-04-09 57 views
1

我有一個通用的抽象類Plot<T>。我如何定義一個可以接受抽象類的實現的集合?我曾嘗試以下方法沒有成功:定義一個集合,接受任何通用類的實現

public List<Plot<object>> Plots = new List<Plot<object>>();

public List<Plot<dynamic>> Plots = new List<Plot<dynamic>>();

感謝。

+0

'class PlotList :List > {}' – leppie 2013-04-09 18:49:24

+0

您不能創建此集合,因爲C#中的泛型是在編譯時定義的。 – 2013-04-09 18:53:51

回答

8

情況是這樣,通常要求創建一個非泛型基類,從通用類派生:

public abstract class Plot 
{ 
    // Put anything which doesn't need T here 
} 

public class Plot<T> : Plot 
{ 
} 

然後你就可以創建一個List<Plot>

+0

我已經在許多項目中使用過這種技術。我在Tim McCarthy的「Domain Driven Design」一書中首次發現了這個問題。 http://www.amazon.com/NET-Domain-Driven-Design-Problem-Solution/dp/0470147563/ref=sr_1_5?ie=UTF8&qid=1365533533&sr=8-5&keywords=domain+driven+design – krillgar 2013-04-09 18:53:20

相關問題