What is the purpose of accessors?

后端 未结 6 776
萌比男神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:04

    Simply put, get and set accessors are the functions called on a Property; that is, when you retrieve the value or when you set it. It forces a type of behavior on the way values are retrieved or set.

    For example, you may want to have a mechanism to get/set passwords. Generally speaking, you'll only want to compare the hash of a password instead of storing things plaintext, so you'd have the getter variable retrieve the stored hash, and the setter would take the provided input and hash it for storage.

    Here's what I mean:

    public class User {
        //Usery properties here, and...
        private string _password;
        public string Password {
            get {
                return _password;
            }
            set {
                _password = SomeHashingFunction(value);
            }
        }
    }
    

    value is the variable provided to the setter from what has been given in the variable assignment. e.g.: someuser.Password = "blah";

提交回复
热议问题