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