C#初始化嵌套类和外部类会产生Null引用



我有以下代码:

using System;
using System.Collections.Generic;
public class XTRAsystem
{
public string version
{ get; set; }
public XTRAapi api
{ get; set; }
public XTRAsystem(string system_version)
{
this.version = system_version;
XTRAapi api = new XTRAapi(Guid.NewGuid());
Console.WriteLine("New XTRA system (" + this.version + ") initialized.");
}
public class XTRAapi
{
public Guid id
{ get; set; }
public string name
{ get; set; }
public XTRAapi(Guid Id)
{
this.id = Id;
Console.WriteLine("New T24 API created.");
}
}
}
public class testCase
{
public int caseNumber
{ get; set; }
public List<string> data;
public XTRAsystem refSystem
{ get; set; }
public testCase()
{
data = new List<string>();
Console.WriteLine("New Test Case created.");
}
}

上面的两个类是嵌套的,这是有原因的。现在,在我的Main程序中,下面的代码会产生Null引用异常。有人能帮我吗?

using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Start..");
XTRAsystem mySystem = new XTRAsystem("Mickey");
testCase[] myTest = new testCase[100];
Console.WriteLine("Capacity is {0}", myTest.Length);
//  'Object reference not set to an instance of an object' for all the below
myTest[0].caseNumber = 1;
myTest[0].data.Add("first test");
myTest[0].data.Add("second test");
myTest[0].data.Add("third test");
myTest[0].refSystem = mySystem;
}
}
}

根据您的专业知识和经验,是否有其他方法可以产生现在会产生错误的功能(行myTest[0]…等(非常感谢

在使用属性之前,您必须初始化每个数组项

testCase[] myTest = new testCase[100];
Console.WriteLine("Capacity is {0}", myTest.Length);
myTest[0] = new testCase();

myTest[0].caseNumber = 1;
// also, initialize your list
myTest[0].data = new List<string>();

最新更新