What is the purpose of accessors?

后端 未结 6 784
萌比男神i
萌比男神i 2021-02-13 02:09

Can somebody help me understand the get & set?
Why are they needed? I can just make a public variable.

6条回答
  •  醉梦人生
    2021-02-13 03:15

    Properties act as accessors to the internal state of an object, hiding the implementation of that state.

    So, for example, you may have a first name property in a class

    public class Example
    {
        private string firstName;
    
        public string FirstName
        {
            get {return this.firstName;}
        }
    }
    

    So anyone using the class doesn't need to know how first name is stored, they just know they can get a string representation of it. By adding a set you also add a mutator, something which changes an objects internal state

    public class Example
    {
        private string firstName;
    
        public string FirstName
        {
            get {return this.firstName;}
            set {set this.firstName = value;}   
        }
    }           
    

    Again you're still isolating how the first name is stored internally (encapsulation), but users can change it by passing in a string.

提交回复
热议问题