以下是我的代码的简化版本:
class House
{
private string owner;
private int[] roomArea = new int[10];
public string Owner { get; set; }
public int[] RoomArea { get; set; }
}
class Program
{
static void Main(string[] args)
{
House[] london = new House[100];
for (int i = 0; i < 100; i++)
{
london[i] = new House();
}
london[0].Owner = "Timmy";
london[0].RoomArea[0] = 15; // Error points to this line
Console.WriteLine("Room 1 in " + london[0].Owner + "s house has the area of " + london[0].RoomArea[0] + "square meters");
}
}
我收到以下错误:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
我看过这个this question/solution,但我无法确定代码的确切错误。
答案 0 :(得分:2)
您需要初始化 RoomArea
。即使你在类中初始化它正在创建它自己的成员,但是为了添加你需要初始化它的值
london[0].RoomArea = new int[10];
london[0].RoomArea[0] = 15;