Dart,无法调用Generic的方法 [英] Dart, Can't call Generic's method
问题描述
我正在尝试创建一个抽象数据模型,在该模型中我传递数据并键入a,然后返回列表,但是当我无法调用 T.fromJson()
时方法,请注意,传递类型具有方法 fromJson()
I am trying to create an abstract data model where i pass data and type a and then is return list, but when i can't call T.fromJson()
method, note that passes type has method fromJson()
class DataList<T> {
final bool success;
dynamic data;
InfosResponse({
this.success,
List<dynamic> data,
}) {
castDataToList(data);
}
factory DataList.fromJson(Map<String, dynamic> json) {
return DataList(
success: json['success'],
data: json['data'],
);
}
void castDataToList(jsonData) {
this.data = List<T>.from(jsonData.map((x) => T.fromJson(x)));
}
}
推荐答案
您无法在类型变量上调用静态方法。静态方法必须在编译时已知,并且类型变量的值要在运行时才知道。
You cannot call static methods on type variables. Static methods must be known at compile-time, and the value of a type variable is not known until run-time.
您可以使用您所使用的方法对类进行参数化要调用:
You can parameterize your class with the method that you want to call:
class DataList<T> {
final bool success;
dynamic data;
T dynamic Function(Object) fromJson;
DataList({
this.success,
List<dynamic> data,
this.fromJson;
}) {
castDataToList(data);
}
factory DataList.fromJson(Map<String, dynamic> json, T fromJson(Object o)) {
return DataList(
success: json['success'],
data: json['data'],
fromJson: fromJson,
);
}
void castDataToList(jsonData) {
this.data = List<T>.from(jsonData.map((x) => fromJson(x)));
}
}
当您要使用具有某种类型的类时, Foo
具有 fromJson
静态方法,您将实例创建为:
When you want to use the class with a type, Foo
which has a fromJson
static method, you create the instance as:
var dataList = DataList<Foo>fromJson(someJsonMap, Foo.fromJson);
这会将 Foo.fromjson
函数传递给该类,然后可以在需要时使用它。
This passes the Foo.fromjson
function to the class, which can then use it when needed.
这篇关于Dart,无法调用Generic的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!