在C#中使用数组的NullReferenceException

Wil*_*ill 1 c# arrays nullreferenceexception

我想创建一个包含我正在处理的所有Pushpin对象的数组.在尝试填充Array时,我收到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++;
                }
Run Code Online (Sandbox Code Playgroud)

和...

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++;
                 }
Run Code Online (Sandbox Code Playgroud)

似乎没有任何工作......我每次都会得到NullReference错误.有任何想法吗?非常感谢!将.

Ami*_*ira 6

问题是你没有初始化你的数组:

Pushpin[] arrayPushpins = new Pushpin[10]; // Creates array with 10 items
Run Code Online (Sandbox Code Playgroud)

IEnumerable<Pushpin>如果您事先不知道物品的数量,可以考虑使用,例如:

IEnumerable<Pushpin> pushpins = new List<Pushpin>
Run Code Online (Sandbox Code Playgroud)

  • 为什么不使用`IEnumerable`集合呢? (2认同)