從宣告一個Class開始
因為之前是學Java,所以習慣物件導向,自然習慣了「寫程式,從怎麼寫物件開始。」
void main(){
var D = new Demo('Dart Tutorial', 'Happy coding', '2019/9/14');
print(D.title);
}
class Demo {
String title; //標題
String description; //資訊
String publishTime; //時間
Demo(String title, String description, String publishTime) {
this.title = title;
this.description = description;
this.publishTime = publishTime;
}
}以上可以看到一個標準物件的結構。
一個物件只能有一個建構子。這是比較奇妙的地方。
void main() {
var d1 = new Demo('Dart Tutorial', 'Happy coding', '2019/9/14);
print(d1.title); //Output: Dart Tutorial
var d2 = new Demo.onlyDescription("Happy coding Only Description");
print(d2.url); //Output: https://123.456
var d3 = new Demo.onlyTitle("Dart Tutorial Only title");
print(d3.title); //Output: Only title
}
class Demo {
String _title; //標題 增加下引線表示這是private
String _description; //影片資訊 增加下引線表示這是private
String _publishTime; //上傳時間 增加下引線表示這是private
Demo(this._title, this._description, this._publishTime);
Demo.onlyDescription(this._description);
Demo.onlyTitle(String title){
this._title = title;
}
//getter
String get title => this._title;//大概是因為private所以提供getter
String get url => this._url;//大概是因為private所以提供getter
//setter
set title(String title) {//大概是因為private所以提供setter
this._title = title;
}
}
變數前面增加一個下引線,表示這個參數為private。
Demo.onlyDescription()和Demo.onlyTitle()可以做為多重建構子使用,說是「比較好閱讀」。(但我覺得如果要好閱讀,為什麼不使用Builder Module?)
可以看到建構子中直接使用「this._參數名稱」來快速將建構子接收到的數值傳入相對的參數內,不知道是否有省去「宣告區域變數」的步驟進而提升效能,或只是單純地讓程式碼變少?(有空來寫測試看看。)
為什麼會有get/set這組指令字元,原因不明;可否不使用,需要測試,或再找找答案。
留言
張貼留言