Encapsulation C# newbie

前端 未结 5 975
我在风中等你
我在风中等你 2021-01-02 22:54

New to C#, and I understand that encapsulation is just a way of \"protecting data\". But I am still unclear. I thought that the point of get and set accessors wer

5条回答
  •  鱼传尺愫
    2021-01-02 23:22

    Indeed, creating an auto-property as follows:

    public string Name { get; set; }
    

    is identical to building a property backed by a field:

    private string _name;
    public string Name {
        get { return _name; }
        set { _name = value; }
    }
    

    The point of these properties is not to hide data. As you observed, they don't do this. Instead, these properties can do other stuff instead of just working with a field:

    public string Name {
        get { return _name; }
        set { if (value == null) throw new Exception("GTFO!"); _name = value; }
    }
    

    Another thing is, you can make properties virtual:

    public virtual string Name { get; set; }
    

    which, if overridden, can provide different results and behaviours in a derived class.

提交回复
热议问题