如何使泛型语言以Dart语言工作?

时间:2018-10-25 21:00:09

标签: generics dart flutter

我对Dartclass 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”实例中的方法,为什么会出现错误?

1 个答案:

答案 0 :(得分:4)

您需要通知编译器您的泛型实现了特定的接口:

abstract class DoSomething {
  void something();
}

class Shape<T extends DoSomething> {
  T value;

  foo() {
    // works fine
    value.something();
  }
}