2014-06-17 57 views
0

我有這個Car類,爲什麼我不能初始化我的Garage類?

public class Car 
{ 
    public string Name { get; set; } 
    public string Color { get; set; } 

    public Car(): this ("", "") { } 

    public Car(string name, string color) 
    { 
     this.Name = name; 
     this.Color = color; 
    } 
} 

另外我有一個包含Car個集合Garage類。

public class Garage 
    { 
     public List<Car> CarList { get; set; } 

     public Garage() { } 

     public Garage(int carCount) 
     { 
      this.CarList = new List<Car>(carCount); 
     } 

     public Garage(params Car[] cars) 
     { 
      this.CarList = new List<Car>(); 
      foreach (Car car in cars) 
       this.CarList.Add(car); 
     } 
    } 

我試圖在Main()初始化Garage的實例,

Car car1 = new Car("BMW", "black"); 
Car car2 = new Car("Audi", "white"); 
Garage garage = new Garage(car1, car2); 

我得到一個錯誤,「一個字段初始不能引用非靜態字段,方法或屬性」。我做錯了什麼? 「

+2

有在您發佈的代碼中沒有字段初始內部使用。找到正在報告錯誤的行,然後張貼該行。 – dcastro

+2

你的代碼對我來說似乎很好。我認爲你在其他地方有問題 –

+0

請發送你的完整代碼 – Khan

回答

1

」實例字段不能用於初始化方法外的其他實例字段。「 請檢查此頁ERROR page from MS

所以要麼使汽車物體靜態爲;

static Car car1 = new Car("BMW", "black"); 
    static Car car2 = new Car("Audi", "white"); 

    Garage garage = new Garage(car1, car2); 

或者 聲明它

 Car car1 = new Car("BMW", "black"); 
    Car car2 = new Car("Audi", "white"); 
    Garage garagel; 

,然後任何其他方法

garage = new Garage(car1, car2); 
相關問題