2

D语言有'别名...'。Go 有嵌入的字段。在下面的代码中,Dart 是否有办法在不经过内脏的情况下到达啮齿动物的大肠?理想情况下,以某种方式公开内部组件的集合,无需在每个动物中使用一些通用的内部组件创建转发呼叫?

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();
}
4

1 回答 1

2

感谢您对...生物学的兴趣,并且很高兴地说您正在寻找的构造可能是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();
  }
}

或者,如果您希望节省写作工作,您可以拥有一个具有您正在寻找的属性的超类或接口或 mixin(取决于您想要做什么):

class Animal {
  LargeIntestine largeIntestine = new LargeIntestine();
  ...
}

class Rodent extends Animal { ... }

或者

class Rodent extends Object with Animal { ... }

见:http ://www.dartlang.org/articles/mixins/

于 2013-04-09T19:33:46.120 回答