gpt4 book ai didi

generics - 在泛型 Dart 上调用方法

转载 作者:行者123 更新时间:2023-12-02 09:07:52 24 4
gpt4 key购买 nike

我试图找到一种方法来调用泛型类型的方法。但是找不到。

迅速我可以这样写:

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

在 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'.
}

代码给出错误 The method 'createOne' isn't defined for the class 'Type'如何解决这个问题?如果这是可能的,它将节省大量时间和大量代码行。

最佳答案

这不可能。在 Dart 中,您不能通过类型变量调用静态方法,因为静态方法必须在编译时解析,并且类型变量在运行时才具有值。 Dart 接口(interface)不是 Swift 协议(protocol),它们只能指定实例方法。

如果你想参数化一个能够创建一个类型的新对象的类,你需要传递一个函数来这样做:

void floo<T>(T create(), ...) { 
...
T t = create();
...
}

你不能仅仅依靠类型变量。

关于generics - 在泛型 Dart 上调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55901883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com