如何在 Dart 中同时对接口使用受限 mixin 并同时实现该接口?

Dmy*_*ian 5 oop interface mixins dart

我拥有的:

  1. 具有必须重写的方法的接口 (InterfaceA)。
  2. 仅限于接口 mixin (MixinB) 以及我想在不重写的情况下使用的方法。
  3. 具有接口实现和 mixin 使用的类(ClassC)。

问题:是否可以同时使用受限 mixin 与该接口的实现进行交互?

下面的代码是一个示例,展示了我理想情况下如何使用 mixin 和界面

abstract class InterfaceA {
  int getValue();
}

mixin MixinB on InterfaceA {
  int getPreValue(int i) => i;
}

// Error:
// 'Object' doesn't implement 'InterfaceA' so it can't be used with 'MixinB'.
class ClassC with MixinB implements InterfaceA {
  @override
  getValue() => getPreValue(2);
}
Run Code Online (Sandbox Code Playgroud)

lrn*_*lrn 5

您的 mixin 不需要type 类上使用InterfaceA。你可以将其声明为

mixin MixinB implements InterfaceA {
  in getPrevAlue(int i) => i;
}
Run Code Online (Sandbox Code Playgroud)

反而。然后使用 mixin 需要 mixin 应用程序类来实现InterfaceA,因为 mixin 不提供实现,但它可以在 mixin 中混合之前或之后提供实现。那么你的代码将是:

class ClassC with MixinB { // no need for `implements InterfaceA`
  @override
  getValue() => getPreValue(2);
}
Run Code Online (Sandbox Code Playgroud)

仅当您需要使用调用类型上的超级接口成员on时,才对 mixin 使用要求。否则,仅用于确保生成的对象将实现该接口。您仍然可以在界面上进行正常的虚拟呼叫。onsuper.memberNameimplements

例子:

abstract class MyInterface {
  int get foo;
}
mixin MyMixin implements MyInterface {
  int get bar => this.foo; // Valid!
}
class MyClass with MyMixin {
  @override
  int get foo => 42;
  int useIt() => this.bar; // returns 42
}
Run Code Online (Sandbox Code Playgroud)