Public Fields versus Automatic Properties

前端 未结 12 2094
梦谈多话
梦谈多话 2020-11-21 23:34

We\'re often told we should protect encapsulation by making getter and setter methods (properties in C#) for class fields, instead of exposing the fields to the outside worl

12条回答
  •  情深已故
    2020-11-22 00:24

    My pov after did some researches

    1. Validation.
    2. Allow overriding the accessor to change the behaviour of a property.
    3. Debugging purpose. We'll be able to know when and what the property change by setting a breakpoint in the accessor.
    4. We can have a field set-only. For instance, public set() and private get(). This is not possible with the public field.

    It really gives us more possibility and extensibility.

提交回复
热议问题