gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:42:44 25 4
gpt4 key购买 nike

我很好奇为什么当通过继承的类型参数传入父类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com