Generics 如何使泛型在Dart语言中工作?
我是Dart和类OOP的新手,请帮助我理解我在下面代码注释中提到的问题Generics 如何使泛型在Dart语言中工作?,generics,dart,flutter,Generics,Dart,Flutter,我是Dart和类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
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”实例中的方法,以及为什么会出现错误?您需要通知编译器您的泛型实现了特定接口:
abstract class DoSomething {
void something();
}
class Shape<T extends DoSomething> {
T value;
foo() {
// works fine
value.something();
}
}
您需要通知编译器您的泛型实现了特定接口:
abstract class DoSomething {
void something();
}
class Shape<T extends DoSomething> {
T value;
foo() {
// works fine
value.something();
}
}