繁体   English   中英

C#中带有数组的NullReferenceException

[英]NullReferenceException with an Array in C#

我想创建一个包含所有正在处理的图钉对象的数组。 尝试填充数组时,我收到了抛出NullReferenceException未处理的错误。 我已经阅读了尽可能多的文档,无法弄清正在发生的事情。

我至少尝试了以下方法:

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++;
                }

和...

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错误。 有任何想法吗? 非常感谢! 将。

问题是您不初始化数组:

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

如果您不知道预先的项目数,则可以考虑使用IEnumerable<Pushpin> ,例如:

IEnumerable<Pushpin> pushpins = new List<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++;
                    }

编辑添加:我避免使用原始数组,而是使用类似List<Pushpin>东西

我认为您应该使用列表而不是数组。 这样,您就不必事先知道列表中将包含多少个元素。

在您的代码中,仅声明而不初始化数组。 您需要使用new关键字对其进行初始化。

Pushpin [] arrayPushpins= new Pushpin[50]; 

作为其他答案的建议,您可以使用列表或集合。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM