簡體   English   中英

在構造函數中初始化類的數組

[英]Initialize an array of a class in a constructor

我有一個類Garage有一個屬性是Car的類型數組,這是程序中的另一個類。 我已經嘗試了幾次迭代並在大多數迭代中獲得運行時錯誤。 每當我嘗試運行它時,我都會收到NullRefernceException 這發生在Program類中,我嘗試訪問CarLot數組的length屬性。

我知道這與Garage類的CarLot屬性是一個數組而不僅僅是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} ");
    }
}

在Main中調用無參數構造函數時,可以使用私有變量來初始化數組,而不是為數組使用auto屬性。

例如

private Car[] carLot = new Car[size];
public Car[] CarLot
{
     get { return carLot; }
     set { carLot = value; }
}

或者,在Garage的無參數構造函數中,您可以繼續並在此時初始化數組。

無論哪種方式,都必須先實例化數組,然后才能為其賦值。 http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

我知道這不是你要求的確切事情,但這樣的事情怎么樣? 這不容易嗎?

    static void Main(string[] args)
    {
        var garage = new List<Car>();
        //this is where the exception occurs
        garage.Add(new Car(5, "car model"));
    }

    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} ");
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM