摘要 属性 没有 setter
Abstract property without setter
我正在写一些代码,我发现当我创建一个没有 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.
是的,你有编译时错误,因为不能保证HorsePower
有一个支持字段可以分配给。想象一下,
public class CounterExample : Motorcycle {
// What "set" should do in this case?
public override int HorsePower {
get {
return 1234;
}
}
public CounterExample()
: base(10, 20) {}
}
遇到这种情况this.HorsePower = horsePower;
应该怎么办?
c#中的abstract关键字指定classes或成员,其实现必须由派生class提供。
我正在写一些代码,我发现当我创建一个没有 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.
是的,你有编译时错误,因为不能保证HorsePower
有一个支持字段可以分配给。想象一下,
public class CounterExample : Motorcycle {
// What "set" should do in this case?
public override int HorsePower {
get {
return 1234;
}
}
public CounterExample()
: base(10, 20) {}
}
遇到这种情况this.HorsePower = horsePower;
应该怎么办?
c#中的abstract关键字指定classes或成员,其实现必须由派生class提供。