c#中一个数组的NullReferenceException
本文关键字:一个 数组 NullReferenceException | 更新日期: 2023-09-27 18:08:43
我想创建一个包含我正在处理的所有Pushpin对象的数组。在尝试填充数组时,我得到一个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];
正如其他答案所建议的,您可以使用列表或集合