没有 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。


天涯尽头无女友
浏览 112回答 2
2回答

烙印99

是的,您有编译时错误,因为不能保证有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关键字指定其实现必须由派生类提供的类或成员。
打开App,查看更多内容
随时随地看视频慕课网APP