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

查看:27
本文介绍了在 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"的警告转换为 as 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.

感谢阅读.

推荐答案

这不是错误,而是功能.请参阅 此答案来自 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 的分配兼容性规则还允许从超类型分配到子类型.

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.

换句话说,您可以在赋值中隐式向下转换,而无需任何类型的显式转换.所以这里没有静态警告.但是,如果您在检查模式下运行代码并且向下转换结果是无效的(就像这里一样),那么当您尝试将 double 分配给 x 时,您将在运行时收到类型错误.

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天全站免登陆