dart - Dart 2 与 TypeScript 的 typeof 等价物是什么?
问题描述
我是 Dart 2 的新手。我希望一个类有一个属性。这是其他类的参考。它不是一个实例,而是类本身。在 TypeScript 中,可以编写如下。Dart 2中是否有相同的方法?
class Item { }
class ItemList {
itemClass: typeof Item;
}
const itemList = new ItemList();
itemList.itemClass = Item;
更新:
我添加了更多上下文。以下是最小的示例代码。我想将实例化的角色委托给超类。
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()
方法是否应该被视为方法或构造函数。所以我选择让它成为一种更接近你的代码的方法。
推荐阅读
- python - 将 PLY 文件导出为 NVM
- docker - 如何在 .NET 客户端中为 Docker 获取 docker 日志级别?
- sql - 从外部源导入大量数据集时 Pandas 的最佳实践(使用 SQL)
- python - pyautocad - 块参考自定义选项卡
- python - 无法安装OpenCV python3.8
- tinymce - Tinymce 页面横向设置
- javascript - 计算具有多个表单字段的 pdf 中键入的单词总数。(javascript)
- php - php中的多语言页面
- common-lisp - 方法-泛型-函数是什么意思?
- javascript - 如何在使用样式组件的条件下将边距应用于 div 并做出反应?