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

查看:113
本文介绍了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.

PS:

我不是在寻找解决方案这是为了使用扩展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< dynamic> ;.方法允许的输入是什么? 任何内容

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

Child.method 允许的输入是什么?只是 int s。

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

因此,这样的覆盖可能会违反 Parent< dynamic> 的界面。 (例如,如果您有一个 Child 的实例并将其传递给期望 Parent< dynamic> 的对象,该怎么办,然后调用方法('not 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确实允许您可以使用 协变量关键字以抑制静态类型错误并显式允许覆盖,但请注意,这样做不一定是类型安全的,您将负责确保在运行时不会出现类型错误。

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.

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

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

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