假设我有这样的代码:
class A{ foo() => "A";}
class B{ foo() => "B";}
class C{ foo() => "C";}
class Mix extends A with B,C {
foo() => "MIX";
bar() => super.foo();
}
class MessABC = Object with A,B,C;
class MessBCA = Object with B,C,A;
class MessCAB = Object with C,A,B;
void main() {
Mix mix = new Mix();
MessABC mABC = new MessABC();
MessBCA mBCA = new MessBCA();
MessCAB mCAB = new MessCAB();
print("Mix.foo = ${mix.foo()} Mix.bar = ${mix.bar()} \n"
"mABC.foo = ${mABC.foo()} \n"
"mBCA.foo = ${mBCA.foo()} \n"
"mCAB.foo = ${mCAB.foo()} \n");
}
输出
Mix.foo = MIX Mix.bar = C
mABC.foo = C
mBCA.foo = A
mCAB.foo = B
在mix
对象上,我可以使用超级 调用Mix.foo
和C.foo
(实际上我预期A.foo
)< / EM>
但我可以以某种方式致电A.foo
和B.foo
吗?
我对 with 语义感到有点困惑。 A,B,C
看起来像“一级枚举”,但顺序很重要。而“Dart编辑器”并没有警告我名字冲突。也许我可以启用此警告?
对我来说,这感觉就像是让你感到困惑和容易出错的事情。
答案 0 :(得分:7)
Mixin应用程序从左到右处理。
Object with A,B,C
的超类是Object with A,B
,它再次拥有超类Object with A
,然后是Object
。
mixin的首要规则与非mixin超类相同。 C.foo
中的Mix
会覆盖从A
和B
继承的Mix.bar
,因此super.foo()
&#39; s C.foo
只会到达{{} 1}},无法访问A.foo
或B.foo
。
覆盖是完全正常的,并且不会引起任何警告,只要这些方法具有兼容的签名。
对mixin最全面的描述仍为https://www.dartlang.org/articles/mixins/