Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
调用方法时的C#运行时NullReferenceException_C#_Class_Nullreferenceexception - Fatal编程技术网

调用方法时的C#运行时NullReferenceException

调用方法时的C#运行时NullReferenceException,c#,class,nullreferenceexception,C#,Class,Nullreferenceexception,类定义: public class myClass{ String prop1, prop2,... propn; public void setValues(String input){ prop1 = input.Substring(1,5); prop2 = input.Substring(6,10); ... propn = input.Substring((n-1)*5+1,n*5)); } public getProp1() {return prop1;} public getPro

类定义:

public class myClass{
String prop1, prop2,... propn;
public void setValues(String input){
prop1 = input.Substring(1,5);
prop2 = input.Substring(6,10);
...
propn = input.Substring((n-1)*5+1,n*5));
}
public getProp1() {return prop1;}
public getProp2() {return prop2;}
...
public getPropn() {return propn;}
}
在程序中

    myClass[] Entries = new myClass[50];
    int i=0;
    String Line
    while(i<=49){
    Line = inputFile.ReadLine(); //<--System.NullReferenceException thrown here at run-time
    Entries[i++].setValues(Line);
    }
myClass[]条目=新的myClass[50];
int i=0;
弦线
而(i这条线:

 myClass[] Entries = new myClass[50];
为值创建一个填充了
null
的数组。因此
条目[i++]
将返回一个
null
,从而导致问题中的错误。您可以使用
new
创建您类型的对象,例如:

while(i<=49)
{
    Line = inputFile.ReadLine(); 
    var instance  = new myClass();
    instance.setValues(Line); 
    Entries[i++] = instance ;
}

while(异常实际上在下面的一行,即条目[i++].setValues(行);您的
inputFile
定义在哪里?感谢AStopher。这有助于确定类本身显然是空的,尽管我有一个初始化所有属性的构造函数。[可能是对原始post的扩展,但…]构造函数不应该在创建类数组时执行,并且类的每个实例都应该初始化吗?您好。输入文件是在我前面的代码中使用StreamReader定义的。我可以确认它正在打开,并且“Line”值在watch中显示正确。