Should you access a variable within the same class via a Property?

前端 未结 6 2017
攒了一身酷
攒了一身酷 2020-11-29 07:33

If you have a Property that gets and sets to an instance variable then normally you always use the Property from outside that class to access it.

My question is sho

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 07:50

    Yes I think you should use properties internally in your classes whenever possible. Properties are more flexible and allows you to add logic for validating it's value at a central place.

    You can also delay the initialization of the the field to whenever the property is used instead of being forced to do it in the constructor (or everywhere the field is used). Example:

    class Test {
       private int _checksum = -1;
       private int Checksum {
          get {
             if (_checksum == -1)
                _checksum = calculateChecksum();
             return checksum;
          }
       }
    }
    

提交回复
热议问题