我正在努力实现的目标
我正在尝试创建一个通用Dart方法,该方法采用通用类型T,其中T必须实现类IModel。然而,
问题
看来我不能在T类型上设置implements
约束,而只能设置extends
。例如,<T implements IModel
不起作用,但是<T extends IModel>
起作用。
码
IModel.dart作为接口(interface):
class IModel {
IModel();
factory IModel.fromJson(Map<String, dynamic> json) {
return IModel();
}
Map<String, dynamic> toJson() => {};
IModel clone() {
return IModel();
}
}
WorkControlPlanModel.dart,一个实现IModel的示例:import 'dart:core';
import 'package:knowe_personnelledger_mobile/helpers/DateTimeHelper.dart';
import 'package:knowe_personnelledger_mobile/helpers/StringHelper.dart';
import 'package:knowe_personnelledger_mobile/models/IModel.dart';
class WorkControlPlanModel implements IModel {
String id;
String name;
String companyId;
String projectId;
String description;
DateTime created;
DateTime updated;
WorkControlPlanModel({this.id, this.name, this.description, this.created, this.updated, this.companyId, this.projectId});
factory WorkControlPlanModel.fromJson(Map<String, dynamic> json) {
return WorkControlPlanModel(id: json["id"], name: json["name"], created: DateTime.parse(json["created"]), updated: DateTime.parse(json["updated"]), description: json["description"], companyId: json["companyId"], projectId: json["projectId"]);
}
Map<String, dynamic> toJson() => {
"Id": id,
"Name": name,
"Description": description,
"CompanyId": companyId,
"ProjectId": projectId,
"Created": created.toIso8601String(),
"Updated": updated.toIso8601String()
};
WorkControlPlanModel clone() {
return new WorkControlPlanModel(id: StringHelper.clone(id), companyId: StringHelper.clone(companyId), created: DateTimeHelper.clone(created), updated: DateTimeHelper.clone(updated), name: StringHelper.clone(name), projectId: StringHelper.clone(projectId), description: StringHelper.clone(description));
}
}
使用通用方法的ModelHelper.dart:import 'dart:convert';
import 'package:knowe_personnelledger_mobile/models/IModel.dart';
// 'T implements IModel' not working, but 'T extends IModel' does as constraint.
abstract class ModelHelper {
static List<T> listFromJson<T implements IModel>(String json) {
List l = jsonDecode(json)["data"];
var models = l.map((m) => T.fromJson(m)).toList();
return models;
}
}
其他问题/结论Dart不支持
implements
约束吗?是否所有T类都只需要扩展IModel? 最佳答案
这不是问题。即使对于实现<T extends IModel>
的类,您也可以安全地使用IModel
:
abstract class Abstract {}
class Concrete implements Abstract {}
void function<T extends Abstract>(T value) {
print(value);
}
void main() {
function<Concrete>(Concrete()); // works
}