首页 > 解决方案 > Dart 2.7 通用扩展

问题描述

我在将 dart 1.25 代码转换为 2.7 时遇到问题。我的问题是通用扩展约束。

在较旧的 dart 1.25 版本中,泛型类型在未指定时被理解为 num。

void main() {
  CustomType customType = new CustomType();// no T specified
}

class CustomType<T extends num> {
  CustomType() {
    print(T is num);//> why is this false ?
  }
}

为什么不是这样?

标签: genericsdart

解决方案


您使用了错误的运算符来比较类。利用:

  • ==比较 2 类是否相等
  • is检查对象是否是类的实例。
void main() {
  CustomType customType = new CustomType();// no T specified
}

class CustomType<T extends num> {
  CustomType() {
    print(T);        // num
    print(T == num); // true
    print(1 is num); // true
  }
}

推荐阅读