Implementing read-only properties with { get; }

前端 未结 4 2162
既然无缘
既然无缘 2020-12-19 19:53

Why doesn\'t this run:

  class Program
  {
    static void Main(string[] args)
    {
      Apple a = new Apple(\"green\");
    }
  }

  class Apple
  {

             


        
4条回答
  •  伪装坚强ぢ
    2020-12-19 20:32

    Either add a private setter to your property:

    public string Colour{ get; private set;}
    

    Or add a readonly backing-field:

    private string _colour;
    public string Colour{ get return this._colour; }
    
    public Apple(string colour)
    {
      this._colour = colour;
    }
    

提交回复
热议问题