![](/img/trans.png)
[英]In Dart, what is the difference between using 'new' keyword and directly calling constructor?
[英]Dart: What is the difference when using this keyword and colon after the constructor?
我發現一些代碼讓我對“this”關鍵字和構造函數后的冒號感到困惑。
我想知道兩者之間的區別是什么,以及它們的用途。
使用冒號
class BusinessLogic {
const BusinessLogic({
required DataRepository repository,
}) : _repository = repository;
final DataRepository _repository;
}
使用this
關鍵字
class BusinessLogic {
const BusinessLogic({
required this.repository,
});
final DataRepository repository;
}
在第一個示例中, _repository
是私有成員,在第二個示例中, repository
是公共成員。
除此之外,沒有區別,所以如果你 go 到處都是公共成員,這兩個樣本將是等價的:
class BusinessLogic {
const BusinessLogic({
required DataRepository repository,
}) : repository = repository;
final DataRepository repository;
}
// same as:
class BusinessLogic {
const BusinessLogic({
required this.repository,
});
final DataRepository repository;
}
在 Dart 中,這種構造(在第二個樣本中)稱為“初始化參數”。 您可以在此處閱讀更多相關信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.