来源
import "dart:math";
abstract class Shape<T> {
T getArea();
}
class Circle<T> extends Shape<T> {
T radius;
Circle({required this.radius});
@override
T getArea() => radius * radius * pi;
}
class Square<T> extends Shape<T> {
T length;
Square({required this.length});
@override
T getArea() => length! * length!;
}
void main() {
Circle circle = Circle(radius: 0);
print(circle.getArea());
Circle circle2 = Circle(radius: 10);
print(circle2.getArea());
Square square = Square(length: 20.0);
print(square.getArea());
}
dart编译器生成Error:
Error: The operator '*' isn't defined for the class 'Object'.
- 'Object' is from 'dart:core'.
Try correcting the operator to an existing operator, or defining a '*' operator.
如何在Dart
中使用泛型类型支持基本arithmetic operators
?
1条答案
按热度按时间ghg1uchk1#
你必须定义T可能是什么,否则,如果你乘以两个http客户端会发生什么?
你可以这样做:
下面是一个工作示例:https://dartpad.dev/?id=45feb420bded724ef88772553c4f19db