通过Dart中的子类参数传递超类对象时,没有类型错误 [英] No type error when passing a super class object via a sub class argument in Dart

查看:61
本文介绍了通过Dart中的子类参数传递超类对象时,没有类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么Dart在通过继承的类型参数传递超类时不将其标记为不正确的类型?将继承的类型用作参数意味着继承的类型的接口应该被期望使用,而超类可能没有.这似乎是一个错误吗?

I'm curious as to why Dart doesn't flag a super class as being an incorrect type when it's passed in via an inherited type argument? Taking the inherited type as the parameter means the inherited type's interface should expect to be utilised, which the super class might not have. This seems like a bug?

示例如下:

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'的警告强制转换为ClassTest的 ?我不确定这是否是正常行为,但是我已经碰到了很多.

This brings up no errors in the editor for me. I'd at least expect a warning for 'x' to be cast as ClassTest before being passed? I'm not sure if this is normal behaviour, but I have come across it quite a bit.

感谢阅读.

推荐答案

这不是bug,而是功能.请参阅 Dart小组工程师Bob Nystrom的回答:

It's not a bug, it's a feature. See this answer from Bob Nystrom, engineer on the Dart team:

这里的镖不同.它具有所谓的分配兼容性".确定哪些分配有效.大多数语言为此仅使用常规的子类型化规则:如果将子类型分配给超类型,则分配是安全的.Dart的分配兼容性规则还允许从超类型到子类型进行分配.

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.

换句话说,您可以在分配中隐式向下转换,而无需任何类型的显式强制转换.因此,这里没有静态警告.但是,如果您在检查模式下运行代码,并且向下转换结果无效(如此处所示),则当您尝试为x分配double值时,会在运行时遇到类型错误.

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.

这篇关于通过Dart中的子类参数传递超类对象时,没有类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆