我有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);
}
}
我尝试初始化Garage
中的Main()
实例,
Car car1 = new Car("BMW", "black");
Car car2 = new Car("Audi", "white");
Garage garage = new Garage(car1, car2);
我收到错误,“字段初始化程序无法引用非静态字段,方法或属性”。我做错了什么?
答案 0 :(得分:1)
&#34;实例字段不能用于初始化方法外的其他实例字段。&#34; 请查看此页面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);