为什么我不能初始化我的车库类?

时间:2014-06-17 09:16:28

标签: c# class

我有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);

我收到错误,“字段初始化程序无法引用非静态字段,方法或属性”。我做错了什么?

1 个答案:

答案 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);