Dmy*_*ian 5 oop interface mixins dart
我拥有的:
问题:是否可以同时使用受限 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)
您的 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 使用要求。否则,仅用于确保生成的对象将实现该接口。您仍然可以在界面上进行正常的虚拟呼叫。on
super.memberName
implements
例子:
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)