inheritance - 通过 Dart 中的子类参数传递父类(super class)对象时没有类型错误

标签 inheritance types dart arguments

我很好奇为什么当通过继承的类型参数传入父类(super class)时,Dart 不会将父类(super class)标记为不正确的类型?将继承类型作为参数意味着应该使用继承类型的接口(interface),而父类(super class)可能没有。这似乎是一个错误?

举例如下:

class ClassTest {
  int i;
}

void a(Object x) {
  b(x); // ClassTest inherits Object, but that doesn't mean it has the same interface
}

void b(ClassTest x){
  x.i = 2; // a() can pass a non type safe class to make this fail
}

这对我来说不会在编辑器中出现错误。我至少希望对“x”发出警告 as ClassTest在被通过之前?我不确定这是否是正常行为,但我遇到过很多。

谢谢阅读。

最佳答案

这不是一个错误,这是一个功能。见 this answer from Bob Nystrom, engineer on the Dart team :

Dart is different here. It has something called "assignment compatibility" to determine which assignments are valid. Most languages just use the normal subtyping rules for this: an assignment is safe if you assign from a sub- to a supertype. Dart's assignment compatibility rules also allow assigning from a super- to a subtype.

In other words, you can downcast implicitly in an assignment, without needing any kind of explicit cast. So there's no static warning here. However, if you run the code in checked mode and that downcast turns out to be invalid (as it is here), you will get a type error at runtime when you try to assign a double to x.

关于inheritance - 通过 Dart 中的子类参数传递父类(super class)对象时没有类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31104110/

相关文章:

delphi - 如何继承TObjectList<T>而不是继承TObjectList

c - 警告 : passing argument 3 of 'os' with different width due to prototype

c++ - "' SpaceShip ' does not name a type"即使 SpaceShip 肯定是一种类型

java - 类型层次结构+可选字段

c++ - 在没有 boost 和 c++0x 的情况下安全地进行类型删除

c++ - 如何从派生类访问派生基成员?(在 C++ 中)

JAVASCRIPT 数据类型问题

flutter - 如何在flutter中将图标添加到List View Builder列表中?

c++ - 创建带有图标和透明背景的设备上下文

unit-testing - 如何将unittest.dart包含在我的项目中?