我是Dart
和class
OOP 的新手,请帮助我理解我在下面的代码评论中提到的问题。
main() {
var shape = new Slot<Circle>();
shape.insert(new Circle());
}
class Circle {
something() {
print('Lorem Ipsum');
}
}
class Square {}
class Slot<T> {
insert(T shape) {
print(shape); // Instance of 'Circle'
print(shape.something()); // The method 'something' isn't defined for the class 'dart.core::Object'.
}
}
我的问题是,如何调用“Circle”实例中的方法,为什么会出现错误?
最佳答案
您需要通知编译器您的泛型实现了特定接口(interface):
abstract class DoSomething {
void something();
}
class Shape<T extends DoSomething> {
T value;
foo() {
// works fine
value.something();
}
}
关于generics - 如何使泛型在 Dart 语言中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52998029/