假设我有这样的代码:
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__),但我可以以某种方式调用A.foo和B.foo吗?
此外,我对和语义感到有点困惑。A,B,C看起来像是“一个级别的枚举”,但是顺序很重要。“飞镖编辑”没有警告我名字碰撞。也许我能启用这个警告?
对我来说,这就像是让你困惑和容易出错的东西。
发布于 2014-05-05 05:45:52
混合应用程序从左到右被处理。
Object with A,B,C的超类是Object with A,B,它又有超类Object with A,然后是Object。
混合类的重写规则与非混合类的规则相同。您的C.foo in Mix覆盖了从A和B继承的B,因此Mix.bar的super.foo()只到达C.foo,因此无法访问A.foo或B.foo。
只要方法具有兼容的签名,重写是完全可以的,并且不会引起任何警告。
对混合器最彻底的描述仍然是https://www.dartlang.org/articles/mixins/。
https://stackoverflow.com/questions/23465187
复制相似问题