访问变量"on“类
我需要一个混音,在那里我可以访问一个或多个方法,从它要混入的类。
我发现混音和"on“是起作用的。现在我只需要一张脑海里的照片来记住它为什么会起作用--你能帮上忙吗?
"on“是限制还是继承机制?
首先,这个错误让我开始了,而且从继承的角度来看,"on“和"with”is,“me”都进入了TestErrorClass,而我们只需要一个。
class TestErrorClass with TestErrorMixin {}
mixin TestErrorMixin on TestErrorClass {}
解决方案
这是解决我的问题的方法,我可以使用一个变量,它来自于混音正在进入或限制在其中的类。
class TestSuper {
String variableWeNeedToAccessFromTestMixin = "";
// It will get TestMixin from "on" in TestMixin, it just doesn't know it yet.
// So we can not use the mixin here - fair enough.
void HelloTestSuper(){}
}
// We need "with" here has it will create the same error as described above if we put it on TestSuper.
// Also we need it to be able to call "HelloTestMixin()" both from here and in instances created from this "TestBase" class.
class TestBase extends TestSuper with TestMixin {
void main(){
HelloTestSuper();
HelloTestMixin();
}
}
// "on" is restricted to only be able to being mixed into classes of this type,
// and there for, we can rely on what ever variables being in the SuperClass and use it here.
// Note variable "variableWeNeedToAccessFromTestMixin".
mixin TestMixin on TestSuper {
void HelloTestMixin(){
print(variableWeNeedToAccessFromTestMixin);
}
}
心理画面
现在我可以理解错误,"on“和"with",从继承的角度来看,混合不能在同一个地方结束两次。
但我只能从一个受限的角度来理解这个解决方案,即只允许混音进入TestSuper。
继承与限制
如果它是一个继承问题,那么从"TestSuper“扩展到它应该包括什么是”on“ed,如果它是一个限制问题,那么首先为什么会出现错误。
希望你能看到我的想法,并请问。
谢谢
发布于 2022-03-27 11:13:12
这是Dart语言旅游的节选
有时,您可能希望限制可以使用混合器的类型。例如,mixin可能依赖于能够调用mixin没有定义的方法。如下面的示例所示,您可以通过使用on关键字来指定所需的超类来限制mixin的使用:
class Musician {
// ...
}
mixin MusicalPerformer on Musician {
// ...
}
class SingerDancer extends Musician with MusicalPerformer {
// ...
}
在前面的代码中,只有扩展或实现音乐家类的类才能使用mixin MusicalPerformer。因为SingerDancer扩展了音乐家,SingerDancer可以在MusicalPerformer中混音。
仅仅基于此,用于混合的on
更多地是一种restriction
机制,而不是继承。但是,由于您确切地知道这个受限的混合器将在特定的类(类型)上使用,所以可以使用它的变量和方法。当您考虑到这一点时,类型设置或甚至null安全性都是一样的--如果您确保对象是特定类型的,则可以使用它的方法。
另外,这里是对混合器是如何工作的?的一个很好的解释。
https://stackoverflow.com/questions/71635565
复制相似问题