gpt4 book ai didi

dart - 自动调用转移 - 访问啮齿动物的大肠

转载 作者:行者123 更新时间:2023-12-03 02:58:58 25 4
gpt4 key购买 nike

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

最佳答案

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com