generics - 如何使泛型在 Dart 语言中工作?

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

最佳答案

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

abstract class DoSomething {
  void something();
}

class Shape<T extends DoSomething> {
  T value;

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

关于generics - 如何使泛型在 Dart 语言中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52998029/

相关文章:

c# - 如何避免在服务层上引用 Entity Framework 的需要?

java - 通用工厂模式-如何处理返回类型

ssl - flutter pub 失败 (-10737418819) - 自签名 SSL 证书被阻止?

flutter - 向日期添加天数无法正常工作

java - Java 中通配符泛型的继承

c# - 如何为表单控件创建模板函数?

flutter - 国际象棋应用程序的Flutter倒数计时器(陷入逻辑)

flutter - flutter 的自定义注解,例如Required

flutter - 如何在flutter中覆盖pdf文件?

flutter - 如何在 flutter 中设置库比蒂诺日期选择器的最大日期?