【问题标题】:Abstract property without setter没有设置器的抽象属性
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 谢谢!我试图理解它。如果我们在被覆盖的属性中有设置器,就可以了,对吧? (忽略我们有编译时错误)
  • @Kite:是的,如果我们在abstract(和overriden)属性中都有set,我们保证风雨无阻,我们可以分配值。如果我们仅在 overiden 属性中有set(这是不允许的),那么某些类(如CounterExample)可以没有它,我们在abstract 类中仍然存在问题
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2018-09-16
    • 2017-12-10
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    • 2012-10-02
    • 2020-11-06
    相关资源
    最近更新 更多