【问题标题】:How to call Super Class method if there is a Mixin with a method with the same name如果有一个带有同名方法的 Mixin,如何调用 Super Class 方法
【发布时间】:2019-11-23 22:02:09
【问题描述】:

重复的方法行为

code, here as a Gist, 将打印 e。如果我删除覆盖,即从Baz 删除output,它将从Bar 打印w
这使我得出结论,方法“优先级”是own class->mixin->super class

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

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

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

现在,输出为j。如果我交换BarZoo

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

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

问题

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

为什么

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

补充说明

super.output 也会调用 mixin 方法,这就是它不起作用的原因。您可以尝试将以下构造函数添加到Baz

Baz() {
  super.output();
}

即使这样可行,也无济于事,因为 Flutter 案例中的 dispose 方法是从外部调用的。

【问题讨论】:

  • 这根本不可能。无论如何,在小部件中广泛使用 mixin 通常不是一件好事。它们的可扩展性不是很好

标签: flutter dart


【解决方案1】:

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

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

Dart 中的 Mixin 通过创建一个新类来工作,该类将 mixin 的实现分层到超类之上以创建一个新类——它不是在超类的“侧面”而是“在”超类的“顶部”,所以有如何解决查找没有歧义 source

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 混合器扩展了 P 类,但顺序不同。所有三个 A、B 和 P 类都有一个名为 getMessage 的方法。

我们先调用AB类的getMessage方法,再调用BA类的getMessage方法。

输出将是BA

Want to learn more ? Details Explanation ~>

【讨论】:

    猜你喜欢
    • 2012-03-20
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    相关资源
    最近更新 更多