void Function(int) 不是 void Function(dynamic) 的有效覆盖 [英] void Function(int) isn't a valid override of void Function(dynamic)

查看:23
本文介绍了void Function(int) 不是 void Function(dynamic) 的有效覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Parent<T> {
  void method(T t) {}
}

class Child extends Parent {
  @override
  void method(int i) {} // error: mentioned_below

  void takesDynamic(dynamic d) {
    takesType(d); // no error
  }

  void takesType(int i) {
    takesDynamic(i); // no error
  }
}

错误:

void Function(int) 不是 void Function(dynamic) 的有效覆盖

void Function(int) isn't a valid override of void Function(dynamic)

当我可以在方法参数中轻松地将 int 传递给 dynamic 和反之亦然时,为什么我在覆盖方法时会看到错误.

When I can easily pass int to dynamic and vice-versa in a method parameter, why do I see the error when I override method.

附注:

我不是在寻找使用 extends Parent<int> 并使其工作的解决方案,我想知道为什么当我覆盖方法与调用时会以不同的方式对待事物常规方法.

I am not looking for a solution which is to use extends Parent<int> and get it working, I want to know the reason why things are treated differently when I am overriding a method vs calling regular methods.

推荐答案

void Function(int x) 通常不是 void Function(dynamic x) 因为 int 版本不能替代 dynamic 版本.

void Function(int x) normally isn't a valid override of void Function(dynamic x) because the int version is not substitutable for the dynamic version.

Parent.method 允许的输入是什么?任何.

What are the allowed inputs to Parent<dynamic>.method? Anything.

Child.method 允许的输入是什么?只需 ints.

What are the allowed inputs to Child.method? Just ints.

因此,这种覆盖可能会违反Parent 接口的约定.(例如,如果您有一个 Child 的实例并将其传递给期望 Parent 的对象,然后调用 method('not an int') 就可以了?)

Such an override therefore could violate the contract of Parent<dynamic>'s interface. (For example, what if you had an instance of Child and passed it to something that expected Parent<dynamic>, which then invoked method('not an int') on it?)

(请注意,这并非特定于方法覆盖.通常,不能在需要采用较宽类型的函数的情况下使用采用较窄类型的函数,即使较窄的类型派生自更广泛的类型.)

(Note that this is not specific to method overrides. In general, a function that takes a narrower type cannot be used where a function that takes a wider type is expected, even if the narrower type derives from the wider type.)

Dart 确实允许您使用 covariant 关键字 抑制静态类型错误并明确允许覆盖,但请注意这样做不一定是类型安全的,您将负责确保在运行时不会出现类型错误.

Dart does allow you to use the covariant keyword to suppress the static type error and explicitly allow the override, but be aware that doing so isn't necessarily type-safe, and you would be responsible for ensuring that you don't get type errors at runtime.

进一步阅读:来自维基百科的协方差和逆变(计算机科学)

这篇关于void Function(int) 不是 void Function(dynamic) 的有效覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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