Why do we use .NET properties instead of plain old get/set functions?

前端 未结 15 1683
自闭症患者
自闭症患者 2020-12-25 15:06

I understand the many benefits of providing an interface to access the members of a class indirectly. My question is: isn\'t that already something you can accomplish in jus

15条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-25 15:24

    One of the popular ways of looking at object-oriented programming is to model the classes in our programs on the concepts in our heads.

    The concepts in our heads are based on the actual objects that we perceive around us (whether we perceive them or we communicate with others who have perceived them).

    The objects around us - furniture, animals, space shuttles, etc. - have specific properties and act in specific ways.

    That's where we get properties and methods.

    In C#, a property may not be reducible to a single field-get or field-set (for example, it may require additional checks or there may be caching involved or any number of reasons). So we need a separate concept of properties with get-methods and set-methods to make our programs closer to the concepts we want them to model.

提交回复
热议问题