[英]C# array within an object within an array
这是我的代码的简化版本:
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.
我已经看过这个问题/解决方案 ,但是我无法查明我的代码到底有什么问题。
您需要初始化RoomArea
。 即使您在类内部进行初始化,它仍在创建它自己的成员,但是要添加值,您需要对其进行初始化
london[0].RoomArea = new int[10];
london[0].RoomArea[0] = 15;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.