如果存在具有相同名称的方法的 Mixin,如何调用超类方法

2024-01-26

重复方法行为

The 代码,这里作为要点, https://dartpad.dartlang.org/10e4a4fe0cc01c7eb5ec926ff9a4cebb将打印e。如果我删除覆盖,即删除output from Baz,它将打印w from Bar.
这使我得出结论,方法“优先级”是own class -> mixin -> super class.

如果我添加更多 mixin,例如像这样:

mixin Zoo {
  output() {
    print('j');
  }
}

class Baz extends Foo with Bar, Zoo {
// ...

现在,输出是j。如果我换个位置Bar and Zoo:

class Baz extends Foo with Zoo, Bar {
// ...

现在,输出是w again.
因此,我会这样定义优先级:own class -> last mixin -> nth-last mixin -> super class.

Question

我有什么办法吗control这种行为,即调用超级调用方法,即使mixin有同名的方法吗?

Why

您可能会问为什么我要这样做,而不仅仅是重命名方法。
那么,在 Flutter 中所有State有一个dispose方法,如果我有一个mixin具有dispose方法也是如此,它会破坏State的功能是因为mixin's dispose方法优先,如上所示。

补充笔记

super.output也会调用 mixin 方法,这就是为什么它不起作用。您可以尝试添加以下构造函数Baz:

Baz() {
  super.output();
}

即使这有效,也无济于事,因为disposeFlutter 情况下的方法是从外部调用的。


在混入中 -mixin 的声明顺序非常重要.

当你将 mixin 应用于一个类时,

Dart 中的 Mixin 通过创建一个新类来工作,该新类将 mixin 的实现分层在超类之上以创建一个新类 - 它不是超类的“侧面”而是“顶部”,因此在如何解决查找问题source https://stackoverflow.com/questions/45901297/when-to-use-mixins-and-when-to-use-interfaces-in-dart/45903671#45903671

class A {
  String getMessage() => 'A';
}

class B {
  String getMessage() => 'B';
}

class P {
  String getMessage() => 'P';
}

class AB extends P with A, B {}

class BA extends P with B, A {}

void main() {
  String result = '';

  AB ab = AB();
  result += ab.getMessage();

  BA ba = BA();
  result += ba.getMessage();

  print(result);
}

AB 和 BA 类都使用 A 和 B mixin 扩展了 P 类,但顺序不同。所有三个 A、B 和 P 类都有一个名为 getMessage 的方法。

首先,我们调用AB类的getMessage方法,然后调用BA类的getMessage方法。

输出将是BA.

想了解更多吗?详细说明~> https://medium.com/flutter-community/dart-what-are-mixins-3a72344011f3

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果存在具有相同名称的方法的 Mixin,如何调用超类方法 的相关文章

随机推荐