【问题标题】:Dart: Why does the following code compiles in strong mode?Dart:为什么下面的代码在强模式下编译?
【发布时间】:2016-06-16 07:11:25
【问题描述】:
void main(){
  new C(new A()); // This gives no warning or error
  new D(new A()); // This gives an error

}
class A{}

class B extends A{}

class C {
  B b;
  C(A bb){    this.b = bb;   }
}

class D {  
  B b; 
  D(this.b); 
}

在 main 函数的两个语句中,我将一个 A 类型的实例作为参数。如果我没记错的话,两个语句都应该在强模式下给出错误或警告,但是只有第二个给出错误: 类型检查失败:新的 A()(A) 不是 B 类型

Image showing the code compiled from https://dartpad.dartlang.org/

我刚开始学习 dart 语言,但在文档中找不到此案例的解释。有人知道为什么会这样吗?

【问题讨论】:

    标签: class inheritance dart static-typing


    【解决方案1】:

    看起来您在 C 构造函数中打错了字。你的意思是:

    class C {
      B b;
      C(B/*not A*/ bb){    this.b = bb;   }
    }
    

    【讨论】:

    • 不,实际上错误信息应该在这一行:this.b = bb;,因为 b 的类型是 B,bb 是 A。我想我在这里找到了答案:。 因为向下赋值可能是有效的,而且 Dart 乐观地认为你知道自己在做什么,所以我们也让它们通过静态检查。 我正在做的是向下赋值。 https://www.dartlang.org/articles/why-dart-types/感谢您的快速回复!
    • 就是这样。这是一个隐式向下转型add a flag to disable it有问题
    猜你喜欢
    • 2012-05-28
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 2020-11-02
    • 2021-04-04
    • 1970-01-01
    • 2015-10-14
    相关资源
    最近更新 更多