Kit*_*ite 3 c# properties abstract
我正在编写一些代码,但发现当我创建不带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)
显然,如果要在构造函数中进行设置,则应使用受保护的设置器或公共设置器。
是的,你有编译时错误,因为谁也不能保证,即HorsePower具有支持字段分配给。想像,
public class CounterExample : Motorcycle {
// What "set" should do in this case?
public override int HorsePower {
get {
return 1234;
}
}
public CounterExample()
: base(10, 20) {}
}
Run Code Online (Sandbox Code Playgroud)
this.HorsePower = horsePower;在这种情况下应该怎么办?