Implementing read-only properties with { get; }

前端 未结 4 2161
既然无缘
既然无缘 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:27

    I think what you're looking for is this, which keeps your internal variable protected by only exposing a GET to the outside world. For extra safety you could mark _colour as readonly so that it can't be changed within the class itself either (after instantiation), but I think that's overkill. What if your apple gets old and needs to turn brown ?!

    class Program
    {
        static void Main(string[] args)
        {
            Apple a = new Apple("green");
        }
    }
    
    class Apple
    {
        private string _colour;
        public string Colour
        {
            get
            {
                return _colour;
            }
        }
    
        public Apple(string colour)
        {
            this._colour = colour;
        }
    
    }
    

提交回复
热议问题