作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图找到一种方法来调用泛型类型的方法。但是找不到。
迅速我可以这样写:
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
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/
我是一名优秀的程序员,十分优秀!