2012-02-14 18 views
4

我正在嘗試爲ASP.NET MVC2中的模型類創建一個接口,並且我想知道是否可以在另一個接口中使用List<interface>。如果我給出一個代碼示例,那會更好。在另一個接口C#中使用列表<interface>#

我有兩個接口,一個終端可以有多個托架。所以我編寫我的接口,如下所示。

灣接口​​:

public interface IBay 
{ 
    // Properties 
    int id {get; set;} 
    string name {get;set;} 
    // ... other properties 
} 

終端接口:

public interface ITerminal 
{ 
    // Properties 
    int id {get;set;} 
    string name {get;set;} 
    // ... other properties 
    List<IBay> bays {get;set;} 
} 

我的問題是,當我基於這些接口我如何建立海灣列表實現我的課。我將不得不在ITerminal界面之外以及具體實現內部執行托架列表嗎?

我的目標是能夠做到以下幾點:

具體實現:
灣類別:

class Bay : IBay 
{ 
    // Constructor 
    public Bay() 
    { 
     // ... constructor 
    } 
} 

終端類:

class Terminal : ITerminal 
{ 
    // Constructor 
    public Terminal() 
    { 
     // ... constructor 
    } 
} 

然後能夠訪問這樣的海灣清單

Terminal.Bays 

任何幫助/建議將不勝感激。

+2

你的代碼看起來很好,除了一般的設計建議,海灣應該是'IList '。有關它不起作用? – 2012-02-14 19:16:30

+0

我不確定我是否理解對不起。 ITerminal接口意味着您需要將'Bays'訪問器添加到您的終端對象,然後您可以創建'List '並向其添加'Bay'對象,然後從訪問器返回它。或者你的意思是如何設置它,以便你可以返回一個'List '作爲'List '? – Rup 2012-02-14 19:18:33

+0

@ChrisShain:這更像是一個結構問題和最佳實踐。 – Gnex 2012-02-14 21:50:05

回答

4

這應該很好。只要認識到你的終端類將仍然包含一個List<IBay>,可以根據需要填充Bay實例。 (請注意,我會建議使用IList<IBay>代替,但是。)

如果你想端返回的具體Bay類型,那麼你就需要重新設計你的終端接口,並修改此爲:

public interface ITerminal<T> where T : IBay 
{ 
    // Properties 
    int Id {get;set;} 
    string Name {get;set;} 
    IList<T> Bays {get;} 
} 

public Terminal : ITerminal<Bay> 
{ 
    private List<Bay> bays = new List<Bay>(); 
    IList<Bay> Bays { get { return bays; } } 
    // ... 
    public Terminal() 
    { 
     bays.Add(new Bay { //... 

但是,增加這種複雜性可能沒有什麼價值。

+1

+1:假如終端將始終具有同類的海灣列表(即相同類型或共享基類型),我個人更喜歡這種方法(泛型)。 – Douglas 2012-02-14 21:53:03

+0

非常感謝。我會採取一些答案,並將其與上述的@Douglas結合起來。 – Gnex 2012-02-14 21:53:28

+0

@Douglas:是的海灣總是有相同的類型,所以我會實現這樣的界面。 – Gnex 2012-02-14 21:59:00

6

您可以通過填充具體實例來初始化接口列表。例如,初始化使用object and collection initializersTerminal類,你可以使用類似代碼:

Terminal terminal = new Terminal 
{ 
    id = 0, 
    name = "My terminal", 
    bays = new List<IBay> 
    { 
     new Bay { id = 1, name = "First bay" }, 
     new Bay { id = 2, name = "Second bay" }, 
     new Bay { id = 3, name = "Third bay" }, 
    } 
}; 

幾點有關代碼:

  • 按照慣例,所有的公共屬性應PascalCased。使用IdID而不是id; Name而不是name; Bays而不是bays
  • 由於您非常重視界面,您應該考慮將bays屬性的類型從List<IBay>更改爲IList<IBay>。這將允許消費者爲其分配IBay[]陣列。
+0

謝謝。這是一個關於如何設置我的界面的問題。我不清楚最佳做法是什麼。你的回答給了我我正在尋找的東西。非常感謝你。 – Gnex 2012-02-14 21:48:42

相關問題