将运行时类型作为泛型函数参数传入



我是一名 Swift 开发人员,刚接触 Dart。我正在尝试编写一些通用方法。

我想知道我是否可以在Dart中实现类似的事情。

//Swift version
public func modelFrom<T: Mappable>(response: Encodable?, model: T.Type) -> T? {
if let response = response, let string = response.jsonString {
return T(JSONString: string)
}
return nil
}
// The method can be called like this
let responseModel = modelFrom(response: response, model: FoodLogModel.self)

对于 Dart,我可以转换泛型类的类型吗?就像 Swift 中的<T: Mappable>一样?

Dart 中的runtimeType等同于 Swift 中的<ClassName>.self吗?

非常感谢

这是我尝试过的,

import 'package:dartson/dartson.dart';
import 'package:mobile_corelib/base/model.dart';
T requestFrom<T>(BaseModel model, Type T) {
try {
var dson = new Dartson.JSON();
var object = dson.map(dson.encode(model), T.runtimeType);
return object;
} catch(error) {
return null;
}
}
var dick = requestFrom(model, AccessTokenRequest().runtimeType)

但是我不知道如何在Class type中通过.我应该使用dynamic吗?或Type

Dart 中的runtimeTypeType类型的值,这与在泛型类型参数中编写类型时发生的情况不同。

例如,new List<String>()有效,但new List<''.runtimeType>()是语法错误。

一般来说,Type是相当有限的。不能使用它来创建新实例,除非你位于可以使用镜像的 VM 中。

最新更新