dart - Dart 2与TypeScript的 `typeof`等效吗?

标签 dart dart-2

我是Dart 2的新手。我希望一个类拥有一个属性。它是其他类的引用。 ,它不是实例,而是类本身。 在TypeScript中,可以如下编写。 Dart 2中有相同的方式吗?

class Item { }

class ItemList {
    itemClass: typeof Item;
}

const itemList = new ItemList();
itemList.itemClass = Item;

更新:
我添加了更多上下文。以下是最少的示例代码。我想将实例化角色委派给父类(super class)。

class RecordBase {
    id = Math.random();
    toJson() {
        return { "id": this.id };
    };
}

class DbBase {
    recordClass: typeof RecordBase;
    create() {
        const record = new this.recordClass();
        const json = record.toJson();
        console.log(json);
    }
}

class CategoryRecord extends RecordBase {
    toJson() {
        return { "category": "xxxx", ...super.toJson() };
    };
}

class TagRecord extends RecordBase {
    toJson() {
        return { "tag": "yyyy", ...super.toJson() };
    };
}

class CategoryDb extends DbBase {
    recordClass = CategoryRecord;
}

class TagDb extends DbBase {
    recordClass = TagRecord;
}

const categoryDb = new CategoryDb();
categoryDb.create();

const tagDb = new TagDb();
tagDb.create();

最佳答案

我试图使您将示例代码放入Dart。如前所述,您无法获取对类的引用,并且无法在运行时基于该引用调用构造函数。

但是您可以引用构造类对象的方法。

import 'dart:math';

class RecordBase {
  static final Random _rnd = Random();

  final int id = _rnd.nextInt(100000);

  Map<String, dynamic> toJson() => <String, dynamic>{'id': id};
}

abstract class DbBase {
  final RecordBase Function() getRecordClass;

  RecordBase record;
  Map<String, dynamic> json;

  DbBase(this.getRecordClass);

  void create() {
    record = getRecordClass();
    json = record.toJson();
    print(json);
  }
}

class CategoryRecord extends RecordBase {
  @override
  Map<String, dynamic> toJson() {
    return <String, dynamic>{'category': 'xxxx', ...super.toJson()};
  }
}

class TagRecord extends RecordBase {
  @override
  Map<String, dynamic> toJson() {
    return <String, dynamic>{'tag': 'yyyy', ...super.toJson()};
  }
}

class CategoryDb extends DbBase {
  CategoryDb() : super(() => CategoryRecord());
}

class TagDb extends DbBase {
  TagDb() : super(() => TagRecord());
}

void main() {
  final categoryDb = CategoryDb();
  categoryDb.create(); // {category: xxxx, id: 42369}

  final tagDb = TagDb();
  tagDb.create(); // {tag: yyyy, id: 97809}
}

我不太确定create()方法是否应视为方法或构造函数。因此,我选择使其更接近您的代码。

关于dart - Dart 2与TypeScript的 `typeof`等效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61555818/

相关文章:

dart - 在 Dart 中扩展 Exception 类

dart - 从 Flutter 中的 List<Widget> 中删除 Index wise CustomWidget

dart - pub全局激活命令-$ HOME/.pub-cache/bin不在路径上

android - FLutter中可滚动列中的4个水平Listview

dart - Dart 2 中的 const 何时是可选的?

webstorm - 无法与适用于 Web 的 Angular 和适用于移动项目的 Flutter 一起运行 Dart 2 - 计划共享代码

dart - 如何在Dart中过滤条件列表

regex - 如何从 Dart 中的字符串中仅删除符号

dart - Rikolo流可以使用可选路线段吗?