Public Fields versus Automatic Properties

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

    If you decide later to check that the title is unique, by comparing to a collection or a database, you can do that in the property without changing any code that depends on it.

    If you go with just a public attribute then you will have less flexibility.

    The extra flexibility without breaking the contract is what is most important to me about using properties, and, until I actually need the flexibility, auto-generation makes the most sense.

提交回复
热议问题