为什么我不能初始化车库类?
本文关键字:初始化 不能 为什么 | 更新日期: 2023-09-27 18:09:00
我有这个Car
类,
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;
}
}
我也有Garage
类包含Car
s的集合。
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);
我得到一个错误,"字段初始化器不能引用非静态字段、方法或属性"。我做错了什么?
"实例字段不能用于初始化方法外部的其他实例字段。"
让car对象static为;
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);