Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无setter的抽象属性_C#_Properties_Abstract - Fatal编程技术网

C# 无setter的抽象属性

C# 无setter的抽象属性,c#,properties,abstract,C#,Properties,Abstract,我正在编写一些代码,我发现当我在没有setter的情况下创建一个新的抽象属性时,我无法在构造函数中设置它的值。当我们使用普通属性时,为什么这是可能的?有什么区别 protected Motorcycle(int horsePower, double cubicCentimeters) { this.HorsePower = horsePower; //cannot be assigned to -- it is read only this.CubicCentimeters =

我正在编写一些代码,我发现当我在没有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; }
很明显,如果我们想在构造函数中设置它,我们应该使用受保护的或公共的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) {}
 }

这个应该是什么。马力=马力在这种情况下如何?

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

因为它是abstract@ZoharPeled不完全是这样,如果你添加一个
集合
它会起作用。@ZoharPeled,这又是什么呢?@DavidG请看Dmitry的答案以获得解释。@ZoharPeled我知道,我只是说你的评论不完全正确。谢谢!我正在努力理解它。如果我们在重写的属性中有setter,它就可以了,对吗?(忽略我们有编译时错误)@Kite@Kite:是的,如果我们在
abstract
(和
overrided
)属性中都设置了
集合
,我们就可以保证无论晴雨我们都可以赋值。如果我们只在overiden属性中设置了
集合
(这是不允许的),那么一些类(比如
反例
)很可能没有它,并且在
抽象
类中仍然存在问题