我对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”实例中的方法,为什么会出现错误?
答案 0 :(得分:4)
您需要通知编译器您的泛型实现了特定的接口:
abstract class DoSomething {
void something();
}
class Shape<T extends DoSomething> {
T value;
foo() {
// works fine
value.something();
}
}