【问题标题】:In Dart, how can I call a superclass method shadowed by a mixin method?在 Dart 中,如何调用被 mixin 方法遮蔽的超类方法?
【发布时间】:2020-08-18 02:56:28
【问题描述】:

我有一个类A,它扩展了B,并混合了C,如下面的代码。如何让它发挥作用?

class A extends B with C {
  @override
  int getValue() {
    // Call's C's getValue.
    super.getValue();
    // Now I want to call B's getValue. How do I do that?
    return B.getValue(); // Doesn't work.
  }
}

class B {
  int getValue() {
    return 1;
  }
}

class C {
  int getValue() {
    return 2;
  }
}

如何执行 B 的getValue?谢谢。

【问题讨论】:

  • this 对您有帮助吗?
  • 链接的答案仅告诉您如何重新排序 mixin 以使其中一个可以使用 super 调用。它没有提供一种方法来调用它们中的多个,或者从超类中调用成员,所以我认为它不能回答这个问题。

标签: dart


【解决方案1】:

C 中的 mixin 方法遮蔽了B 中的方法,所以不能直接使用super 来引用B 方法。您需要介绍一种访问方式。

您可以做的是在B 类和C mixin 应用程序之间放置一个私有重定向函数:

class A extends B with _Helper, C {
  int getValue() {
    // It's C
    super.getValue();
    // Now I want to get B's getValue how do it?
    return super._getValueFromB();
  }
}
    
class B {
  int getValue() {
    return 1;
  }
}
mixin C {
  int getValue() {
    return 2;
  }
}
mixin _Helper on B {
  int _getValueFromB() => super.getValue();
}

由于mixin应用顺序是B,B-with-_Helper,B-with-_Helper-with-C,所以B-with-_Helper超类的superB_getValueFromB会正确访问它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 2016-07-24
    • 1970-01-01
    • 2011-12-13
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    相关资源
    最近更新 更多