在dart中使用泛型类型的内置运算符

gfttwv5a  于 2023-04-03  发布在  其他
关注(0)|答案(1)|浏览(102)

来源

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

ghg1uchk

ghg1uchk1#

你必须定义T可能是什么,否则,如果你乘以两个http客户端会发生什么?
你可以这样做:

abstract class Shape<T extends num> {
  T getArea();
}

class Circle<T extends num> extends Shape<T> {
  T radius;
  Circle({required this.radius});

  @override
  T getArea() => radius * radius * pi as T;
}

下面是一个工作示例:https://dartpad.dev/?id=45feb420bded724ef88772553c4f19db

相关问题