【发布时间】:2019-08-09 15:18:01
【问题描述】:
我正在写一些代码,我发现当我在没有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; }
很明显,如果我们想在构造函数中设置它,我们应该使用protected或public setter。
【问题讨论】:
-
因为它是抽象的
-
@ZoharPeled 不完全是,如果你添加一个
set它将起作用。 -
@ZoharPeled,这是怎么回事?
-
@DavidG 查看 Dmitry 的回答以获得解释。
-
@ZoharPeled 我知道,我只是说你的评论并不完全正确。
标签: c# properties abstract