有一个包含1000个单元格的数组。我已经放入了50个对象,所以剩下950个单元格(未使用的引用)。
我想循环放置在数组中的50个对象,然后离开循环。 现在,循环进入数组[51],我收到错误:
**Object reference not set to an instance of an object.**
我已经尝试了条件if (array[i] != null)
,但它不起作用。
编辑:(更多代码)
for (i = 0; i < 1000; i++)
{
if (tablica_postaci[i] != null)
{
...(actions)...
}
}
0-49细胞被填满,我没有触及其余部分。仍然存在错误。 我希望我的程序在完成第50个元素后不要采取行动
答案 0 :(得分:1)
以下是一个示例,您只需调用break关键字即可退出循环。
Company[] companies = new Company[1000];
for (int i = 0; i < 50; i++)
{
companies[i] = new Company();
}
for (int i = 0; i < companies.Length; i++)
{
if (companies[i] == null)
{
break;
}
}
答案 1 :(得分:1)
为什么不直接使用where
子句然后遍历数组?
var itemsThatAreNotNull = array.Where(a => a != null);
foreach (var item in itemsThatAreNotNull)
{
// do whatever you want to do with the item
Console.WriteLine(item.SomeProperty);
}