为了账号安全,请及时绑定邮箱和手机立即绑定

没有 setter 的抽象属性

没有 setter 的抽象属性

C#
天涯尽头无女友 2023-08-20 14:46:59
我正在编写一些代码,我发现当我创建一个没有设置器的新抽象属性时,我无法在构造函数中设置它的值。为什么当我们使用普通属性时会出现这种情况?有什么不同?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。
查看完整描述

2 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

是的,您有编译时错误,因为不能保证有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;这种情况应该怎么办?


查看完整回答
反对 回复 2023-08-20
?
狐的传说

TA贡献1804条经验 获得超3个赞

C#中的abstract关键字指定其实现必须由派生类提供的类或成员。



查看完整回答
反对 回复 2023-08-20
  • 2 回答
  • 0 关注
  • 70 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信