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);
我得到一個錯誤,「一個字段初始不能引用非靜態字段,方法或屬性」。我做錯了什麼? 「
有在您發佈的代碼中沒有字段初始內部使用。找到正在報告錯誤的行,然後張貼該行。 – dcastro
你的代碼對我來說似乎很好。我認爲你在其他地方有問題 –
請發送你的完整代碼 – Khan