プログラム内の別のクラスであるGarage
type の配列であるプロパティを持つクラスがあります。Car
何度か繰り返してみましたが、ほとんどで実行時エラーが発生しました。NullRefernceException
実行しようとするたびに取得します。これは、配列 Program
の長さプロパティにアクセスしようとするクラスで発生します。CarLot
CarLot
これは、クラスのプロパティGarage
が単なる ではなく配列であることと関係があることを知っていますCar
。プログラムが配列を使用しようとしたときに配列が null に設定されないように、ここで欠けている部分は何ですか?
class Program
{
static void Main(string[] args)
{
Garage g = new Garage();
//this is where the exception occurs
g.CarLot[0] = new Car(5, "car model");
Console.ReadLine();
}
}
public class Garage
{
public Car[] CarLot { get; set; }
public Garage() { }
//this should be able to be 0 or greater
public Garage(params Car[] c)
{
Car[] cars = { };
CarLot = cars;
}
}
public class Car
{
public int VIN { get; set; }
public int Year { get; set; }
public string Model { get; set; }
public Car(int _vin, string _model)
{
_vin = VIN;
_model = Model;
}
public Car() { }
public void Print()
{
Console.WriteLine("Here is some information about the car {0} and {1} ");
}
}