[英]Is it possible to define an abstract named constructor in Dart?
我正在嘗試創建一個抽象類Firestorable
,它將確保子類覆蓋命名的構造函數fromMap(Map<String, dynamic> map)
代碼看起來像這樣......
abstract class Firestorable {
/// Concrete implementations will convert their state into a
/// Firestore safe [Map<String, dynamic>] representation.
Map<String, dynamic> toMap();
/// Concrete implementations will initialize its state
/// from a [Map] provided by Firestore.
Firestorable.fromMap(Map<String, dynamic> map);
}
class WeaponRange implements Firestorable {
int effectiveRange;
int maximumRange;
WeaponRange({this.effectiveRange, this.maximumRange});
@override
WeaponRange.fromMap(Map<String, dynamic> map) {
effectiveRange = map['effectiveRange'] ?? 5;
maximumRange = map['maximumRange'] ?? effectiveRange;
}
@override
Map<String, int> toMap() {
return {
'effectiveRange': effectiveRange,
'maximumRange': maximumRange ?? effectiveRange,
};
}
}
當我這樣做時,我沒有收到任何錯誤,但是當我忽略fromMap(..)
構造函數的具體實現時,我也沒有收到編譯錯誤。
例如,以下代碼將編譯而不會出現任何錯誤:
abstract class Firestorable {
/// Concrete implementations will conver thier state into a
/// Firestore safe [Map<String, dynamic>] representation.
Map<String, dynamic> convertToMap();
/// Concrete implementations will initialize its state
/// from a [Map] provided by Firestore.
Firestorable.fromMap(Map<String, dynamic> map);
}
class WeaponRange implements Firestorable {
int effectiveRange;
int maximumRange;
WeaponRange({this.effectiveRange, this.maximumRange});
// @override
// WeaponRange.fromMap(Map<String, dynamic> map) {
// effectiveRange = map['effectiveRange'] ?? 5;
// maximumRange = map['maximumRange'] ?? effectiveRange;
// }
@override
Map<String, int> convertToMap() {
return {
'effectiveRange': effectiveRange,
'maximumRange': maximumRange ?? effectiveRange,
};
}
}
我不能定義一個抽象的命名構造函數並且讓它成為一個具體類中的 require 實現嗎? 如果沒有,這樣做的正確方法是什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.