官术网_书友最值得收藏!

Accessing private fields

In Dart, as discussed when we covered packages, the privacy is at the library level, but it is still possible to have private fields in a class even though Dart does not have the keywords public, protected, and private. A simple return of a private field's value can be performed with a one-line function:

String getFirstName() => _name;

To retrieve this value, a function call is required, for example, Person.getFirstName(); however, it may be preferable to have a property syntax such as Person.firstName. Having private fields and retaining the property syntax in this manner is possible using the get and set keywords.

Using true getters and setters

The syntax of Dart also supports get and set via keywords:

int get score  => score + bonus; 
set score(int increase)  => score += increase * level; 

Using either get/set or simple fields is down to preference. It is perfectly possible to start with simple fields and scale up to getters and setters if more validation or processing is required.

The advantage of the get and set keywords in a library is that the intended interface for consumers of the package is very clear. Further, it clarifies which methods may change the state of the object and which merely report current values.

主站蜘蛛池模板: 西丰县| 永城市| 邓州市| 靖江市| 青川县| 泸水县| 周至县| 湄潭县| 丽江市| 天柱县| 汝州市| 溧水县| 东光县| 正阳县| 安义县| 阜平县| 天全县| 平武县| 霸州市| 如东县| 南安市| 繁峙县| 东平县| 襄汾县| 建水县| 绥滨县| 青铜峡市| 赤城县| 突泉县| 东安县| 奇台县| 和林格尔县| 姚安县| 沅江市| 玛曲县| 金昌市| 观塘区| 全椒县| 方城县| 庆云县| 玉溪市|