我在changeColors函数的while循环的第二次执行中得到了这个NullReferenceException。
public class myClass {
Tuple<int,int>[] theArray = new Tuple<int, int>[100];
}
public myClass() {
theArray = null;
}
public Tuple<int,int>[] findRedPixels(){
Tuple<int,int>[] myArray = new Tuple<int, int>[100];
int k = 0;
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
if (graph.pixelMap [i, j].color == "red") {
myArray[k]= new Tuple<int,int>(i,j);
k++;
}
}
}
return myArray;
}
public void changeColors(){
while (true) {
theArray = findRedPixels();
foreach (var item in theArray) {
//error appears here in the second time it executes the while loop
Console.WriteLine (item.Item1 );
}
}
}
答案 0 :(得分:1)
你不应该像你一样从函数findRedPixels
返回数组,因为该数组已经使用100
元素初始化,尝试使用List
,因为它为您提供了灵活性,您可以增加在飞行中减小尺寸可能是这样的
public Tuple<int,int>[] findRedPixels(){
List<Tuple<int,int>> myArray = new List<Tuple<int, int>>();
int k = 0;
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
if( graph.pixelMap [i, j].color=="red"){
myArray.Add( new Tuple<int,int>(i,j));
k++;
}
}
}
return myArray.ToArray();
}