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

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.

主站蜘蛛池模板: 乌恰县| 无棣县| 招远市| 横山县| 贵州省| 宜兰县| 和龙市| 郎溪县| 无锡市| 彩票| 高邑县| 湖南省| 灵台县| 吉水县| 高雄市| 镇宁| 遵化市| 新野县| 松潘县| 武强县| 翼城县| 天台县| 滨海县| 长海县| 集安市| 长海县| 湾仔区| 临桂县| 宁远县| 泰州市| 安康市| 南乐县| 乌兰浩特市| 滨州市| 饶平县| 怀来县| 蚌埠市| 长治县| 牡丹江市| 临湘市| 湖北省|