[英]C# Object reference not set to an instance of an object
我在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 );
}
}
}
您不应该像从函数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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.