Public Fields versus Automatic Properties

前端 未结 12 2086
梦谈多话
梦谈多话 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:03

    Changing from a field to a property breaks the contract (e.g. requires all referencing code to be recompiled). So when you have an interaction point with other classes - any public (and generally protected) member, you want to plan for future growth. Do so by always using properties.

    It's nothing to make it an auto-property today, and 3 months down the line realize you want to make it lazy-loaded, and put a null check in the getter. If you had used a field, this is a recompile change at best and impossible at worst, depending on who & what else relies on your assemblies.

提交回复
热议问题