2016-06-14 108 views
0

我是C#的新手,所以這個問題可能很簡單。但是我還沒有找到任何解決方案。問題的將對象添加到空列表

描述:

我想創建和空數組[4]列出的[長度不知道。稍後,我將讀出四個不同的頻道,並用預先創建的對象填充列表。

我做了什麼至今

class objChannel 
{ 
    private int channel; 
    public objChannel(int inputChannel) 
    { 
     channel = inputChannel; 
    } 

    public int Channel {get {return channel;}} 
} 

List<objChannel>[] listChannel = new List<objChannel>[4]; 

listChannel[1].Add(objChannel(1)); 

這並不是因爲錯誤的工作。

現在我有一個變通這樣的:

List<objChannel>[] listChannel = {new List<objChannel> { new objChannel(1) }, 
            new List<objChannel> { new objChannel(2) }, 
            new List<objChannel> { new objChannel(3) }, 
            new List<objChannel> { new objChannel(4) }}; 

然而,這會給我非空列表。

+0

首先你必須實例化'listChannel [1]',然後你可以調用實例方法'Add'。 – Habib

+0

你想要一個'objChannel'的_single_容器,或者你想要'objChannel'的containers_容器_容器? –

回答

3

當你初始化列表的數組,你需要創建空列表以及 像:

List<objChannel>[] listChannel = {new List<objChannel>(), new List<objChannel>(), new List<objChannel>(), new List<objChannel>()}; 

for(int i = 0; i<4; i++) 
{ 
    listChannel[i] = new List<objChannel>(); 
} 
+0

有沒有更少的代碼可以做到這一點?我必須做一個類似的事情,它有17個objChannels。我想避免經常寫'新列表()'。 – paj

+0

是的,在創建listChannel數組後,使用for循環創建新的列表對象,請參閱更新的答案 –

+0

謝謝。我以爲有一些我還不知道的密碼。似乎是,我只需要做'for循環'或'while'的方式。 – paj

1

你的第一個代碼失敗的原因是因爲你必須實例化listChannel[1],然後您只能調用實例方法,如:

listChannel[1] = new List<objChannel>(); 
listChannel[1].Add(new objChannel(1)); 

另一點需要注意的是,數組索引以0開頭,而不是1(雖然不確定在問題中使用的是否是有意的)

+0

感謝@Habib的快速回復。這樣可行。現在我有以下'列表 [] listChannel =新列表 [4]; listChannel [0] =新列表(); listChannel [1] =新列表(); listChannel [2] =新列表(); listChannel [3] =新列表();' – paj