【问题标题】:Why can't Dart infer types in redirecting constructor?为什么 Dart 不能在重定向构造函数中推断类型?
【发布时间】:2023-02-17 00:17:47
【问题描述】:

最小可重现代码:

class Parent {}
class Child extends Parent {}

class Foo<T extends Parent> {
  final T t;
  Foo(this.t);

  Foo.one(Child child) : this(child); // Compile error
}

不能将参数类型“Child”分配给参数类型“T”。

为什么我不能在重定向构造函数中传递Child,换句话说,为什么Dart不知道Child满足T extends Parent关系?虽然我可以

void main() => Foo(Child());

笔记:我正在寻找一个理由为什么我不能那样做。请不要发布使用this(child as T)的答案。

【问题讨论】:

    标签: dart


    【解决方案1】:

    因为代码无效,因为你可以这样做:

    class Monster extends Parent {}
    
    void main() {
      final foo = Foo<Monster>.one(Child());
    }
    

    这是一个问题,因为 Monster 确实从 Parent 扩展而来,但构造函数参数采用 Child,然后尝试将其分配给 T,即 Monster

    如果我们进行了您不希望的更改:

    Foo.one(Child child) : this(child as T);
    

    然后我们会得到错误:

    type 'Child' is not a subtype of type 'Monster' in type cast
    #0      new Foo.one (./bin/example1.dart:8:37)
    #1      main (./bin/example1.dart:14:15)
    #2      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
    #3      _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:26)
    

    所以你不能说 Child 总是可以分配给变量 T,其中 T extends Parent

    【讨论】:

    • 完美的。这就是我要找的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    相关资源
    最近更新 更多