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

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.

主站蜘蛛池模板: 筠连县| 花垣县| 屏东县| 弥勒县| 湟源县| 体育| 绵阳市| 兴仁县| 襄樊市| 荃湾区| 永平县| 类乌齐县| 德兴市| 池州市| 囊谦县| 霍山县| 汾阳市| 织金县| 襄汾县| 临武县| 和顺县| 临清市| 栖霞市| 八宿县| 夏邑县| 惠州市| 柏乡县| 沙洋县| 白水县| 都昌县| 麟游县| 日土县| 阳曲县| 敖汉旗| 莱芜市| 临颍县| 资兴市| 峨眉山市| 老河口市| 河南省| 永新县|