2011-09-15 33 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]; 

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

相关问题