2009-06-30 23 views
0

我創建了一個類,它是這樣的:類Array用[]和IEnumerable

public class MovieTheaterList 
    { 
     public DateTime Date { get; private set; } 
     public int NumTheaters { get; private set; } 
     public Theater[] Theaters { get; private set; } 
    } 

    public class Theater 
    { 
     public string Name; 
    } 

我希望能夠將項目添加到MovieTheaterList類的電影院陣列,但是當我嘗試訪問它它顯示爲IEnumerable類型,並且沒有Add()方法?

我習慣在C/C++的結構和類中使用數組,但是如何在.NET 3.5中向數組添加新項?

+1

數組在C#中是固定大小的,每個槽都是可變的。這可能不是你想要的,所以不要使用數組,請使用其他集合類。一些想法:http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx – 2009-07-01 01:17:00

回答

4

將影院公開爲IList,而不是陣列,您可以從中添加/刪除項目。 例如

public class MovieTheaterList 
{ 
    // don't forget to initialize the list backing your property 
    private List<Theater> _theaterList = new List<Theater>(); 

    public DateTime Date { get; private set; } 
    public int NumTheaters { get; private set; } 

    // set is unnecessary, since you'll just be adding to/removing from the list, rather than replacing it entirely 
    public IList<Theater> Theaters { get { return _theaterList; } } 
} 
+0

@Jeremy,是否有一個原因,你返回一個「IList <>」而不是「List <>」。 – vobject 2009-06-30 23:39:05

+1

pZy - http://stackoverflow.com/questions/400135/c-listt-or-ilistt/400144 – 2009-07-01 00:01:15

1

使用

List<Theater> Theaters { get; private set; } 

代替劇院的陣列。您可以使用它初始化它

Theaters = new List<Theater>(); 

在C#中使用列表通常優先於使用數組。您可以使用ToArray()輕鬆地將數組轉換爲數組,但這樣您不必擔心在創建時正確調整數組的大小,或者更重要的是,在執行期間調整大小。

2

如何通過MovieTheatreClass擴展通用列表來實現此功能。

public class MovieTheatreList : List<Theatre> 
{ 
    public DateTime Date { get; private set; } 
} 

public class Theatre 
{ 
    public string Name; 
} 

這樣,你得到所有的內置列表的東西(如計數,而不必單獨NumOfTheatres屬性來保持)。