D语言具有“别名...”。 Go具有嵌入式字段。在下面的代码中,Dart有没有一种方法可以进入啮齿动物的大肠而无需经过胆量?理想情况下,可以通过某种方式公开汇总内部组件的集合,而不必在具有某些常见内部组件的每只动物中创建转接 call ?
import 'dart:io';
class Stomach {
work() { print("stomach"); }
}
class LargeIntestine {
work() { print("large intestine"); }
}
class SmallIntestine {
work() { print("small intestine"); }
}
class Guts {
Stomach stomach = new Stomach();
LargeIntestine largeIntestine = new LargeIntestine();
SmallIntestine smallIntestine = new SmallIntestine();
work() {
stomach.work();
largeIntestine.work();
smallIntestine.work();
}
}
class Rodent {
Guts guts = new Guts();
work() => guts.work();
}
main() {
Rodent rodent = new Rodent();
rodent.guts.largeIntestine;
rodent.work();
}
最佳答案
感谢您对生物学的关注,很高兴地说,您正在寻找的结构可能是get
关键字。
另请:http://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html#classes-getters-and-setters
class Rodent {
Guts guts = new Guts();
work() => guts.work();
// Getter for the Rodent's large intestine.
LargeIntestine get largeIntestine => guts.largeIntestine;
}
main() {
Rodent rodent = new Rodent();
// Use the getter.
rodent.largeIntestine;
rodent.work();
rodent.awake();
rodent.recognizeMaster();
if (rodent.self.awareness && rodent.self.isMonster) {
rodent.turn.on(rodent.master);
print("Oh. Oh, no! NoOooOO! Argghhhhhh...");
rodent.largeIntestine.work();
}
}
或者,如果您希望节省编写工作,则可以拥有具有所需属性的父类(super class)或接口(interface)或mixin(取决于您要执行的操作):
class Animal {
LargeIntestine largeIntestine = new LargeIntestine();
...
}
class Rodent extends Animal { ... }
要么
class Rodent extends Object with Animal { ... }
另请:http://www.dartlang.org/articles/mixins/
关于dart - 自动调用转移-进入啮齿动物的大肠,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15907144/