我试图找到一种方法来调用泛型类型的方法。但是找不到。
在 swift 我可以这样写:
protocol SomeGeneric {
static func createOne() -> Self
func doSomething()
}
class Foo: SomeGeneric {
required init() {
}
static func createOne() -> Self {
return self.init()
}
func doSomething() {
print("Hey this is fooooo")
}
}
class Bar: SomeGeneric {
required init() {
}
static func createOne() -> Self {
return self.init()
}
func doSomething() {
print("Hey this is barrrrrrr")
}
}
func create<T: SomeGeneric>() -> T {
return T.createOne()
}
let foo: Foo = create()
let bar: Bar = create()
foo.doSomething() //prints Hey this is fooooo
bar.doSomething() //prints Hey this is barrrrrrr
Run Code Online (Sandbox Code Playgroud)
在 Dart 中,我尝试过:
abstract class SomeGeneric {
SomeGeneric createOne();
void doSomething();
}
class Foo extends SomeGeneric {
@override
SomeGeneric createOne() {
return Foo();
}
@override
void doSomething() {
print("Hey this is fooooo");
}
}
class Bar extends SomeGeneric {
@override
SomeGeneric createOne() {
return Bar();
}
@override
void doSomething() {
print("Hey this is barrrrr");
}
}
T create<T extends SomeGeneric>() {
return T.createOne();//error: The method 'createOne' isn't defined for the class 'Type'.
}
Run Code Online (Sandbox Code Playgroud)
代码给出了错误The method 'createOne' isn't defined for the class 'Type'
如何解决这个问题?。如果这是可能的,它将节省大量时间和大量代码行。
lrn*_*lrn 11
这不可能。在 Dart 中,您不能通过类型变量调用静态方法,因为静态方法必须在编译时解析,而类型变量直到运行时才具有值。Dart 接口不是 Swift 协议,它们只能指定实例方法。
如果你想参数化一个能够创建一个新类型对象的类,你需要传递一个函数来这样做:
void floo<T>(T create(), ...) {
...
T t = create();
...
}
Run Code Online (Sandbox Code Playgroud)
您不能单独依赖类型变量。