繁体   English   中英

是否可以在 Dart 中定义一个抽象的命名构造函数?

[英]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 实现吗? 如果没有,这样做的正确方法是什么?

正如 Dart 语言构造函数的官方指南中所述,它不是继承的,因此您不能对子类强制使用工厂构造函数。 为了确保实现,它应该是类的接口的一部分,而构造函数不是。 您可以查看这些相关的 stackoverflow 问题以获取更多信息:

如何在抽象类中声明工厂构造函数

我如何保证 dart 中的某个命名构造函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM