2011-09-15 37 views
1

我想創建一個包含我正在處理的所有圖釘對象的數組。當試圖填充數組時,我得到一個NullReferenceException拋出的未處理錯誤。我已經閱讀了儘可能多的文檔,並且無法弄清楚發生了什麼。NullReferenceException與C中的數組#

我已經試過至少有以下:

Pushpin[] arrayPushpins; 
int i = 0; 
foreach (Result result in arrayResults) 
       { 
        Pushpin pin; 
        pin = new Pushpin(); 
        pin.Location = d; 
        myMap.Children.Add(pin); 
        arrayPushpins[i] = new Pushpin(); 
        arrayPushpins.SetValue(pin, i);; 
        i++; 
       } 

AND ...

Pushpin[] arrayPushpins; 
int i = 0; 
foreach (Result result in arrayResults) 
       { 
        Pushpin pin; 
        pin = new Pushpin(); 
        pin.Location = d; 
        myMap.Children.Add(pin); 
        arrayPushpins[i] = new Pushpin(); 
        arrayPushpins[i] = pin; 
        i++; 
       } 

而且似乎沒有任何工作。我每次都遇到了NullReference錯誤。 任何想法? 非常感謝! 請問。

回答

6

的問題是,你不初始化您的數組:

IEnumerable<Pushpin> pushpins = new List<Pushpin> 
+2

爲什麼不使用IEnumerable集合呢? –

+0

剛剛添加了這個,謝謝:-) –

+0

初始化固定的數組。奇怪的是,我以爲我也嘗試過,但可能不會與使用SetValue方法結合使用。謝謝,阿米泰。我也會嘗試使用一個Collection,因爲我認爲你是對的 - 在這種情況下會更好,因爲引腳數量可能會有所不同。 –

1

Pushpin[] arrayPushpins = new Pushpin[10]; // Creates array with 10 items 

,如果你不提前知道項目的數量,例如,你可能會考慮使用IEnumerable<Pushpin>您沒有初始化陣列

Pushpin[] arrayPushpins = new Pushpin[/*number goes here*/]; 
    int i = 0; 
    foreach (Result result in arrayResults) 
        { 
         Pushpin pin; 
         pin = new Pushpin(); 
         pin.Location = d; 
         myMap.Children.Add(pin); 
         arrayPushpins[i] = new Pushpin(); 
         arrayPushpins.SetValue(pin, i);; 
         i++; 
        } 

編輯添加:我會避免使用原始的a rray,並用類似List<Pushpin>的東西來代替

+0

謝謝gn22。我會嘗試使用一個集合。 :) –

1

我認爲你應該使用列表而不是數組。這樣,您就不必事先知道列表中有多少元素。

+0

同意 - 我會嘗試。謝謝。 :) –

0

在你的代碼中,數組只是聲明的,沒有初始化。你需要用new關鍵字來初始化它。

Pushpin [] arrayPushpins= new Pushpin[50]; 

正如其他答案建議,您可以使用列表或集合。

相關問題