我正在编写一些代码,但发现当我创建不带setter的新抽象属性时,无法在构造函数中设置其值。当我们使用普通属性时,为什么可能这样?有什么不同?
protected Motorcycle(int horsePower, double cubicCentimeters)
{
this.HorsePower = horsePower; //cannot be assigned to -- it is read only
this.CubicCentimeters = cubicCentimeters;
}
public abstract int HorsePower { get; }
public double CubicCentimeters { get; }
Run Code Online (Sandbox Code Playgroud)
显然,如果要在构造函数中进行设置,则应使用受保护的设置器或公共设置器。