Menu
CoddyTech

组合对象

Coddy 面向 C# 开发者的 GDScript 课程的第 29 课,共 48 课。

C# 和 GDScript 的类引用字段可以共享同一个协作者。存储这个引用不会克隆对象,后续的更改仍可通过别名看到。通过构造函数注入协作者,可以观察和测试不同的协作者。生命周期管理有所不同:.NET 垃圾回收可以回收无法访问的托管循环引用,而 RefCounted 的强引用循环不会自动回收。请明确所有权方向,或使用 WeakRef,不要形成循环强引用。这里,信封会观察便笺;练习则会委托一项定价操作。

完成 C# 对比示例。将列出的所有 C# 文件一起编译;Program.Main 是入口点。

C# 文件 DemoNote.cs:

public class DemoNote { public string Text="a"; }

C# 文件 DemoEnvelope.cs:

public class DemoEnvelope { public DemoNote Note; public DemoEnvelope(DemoNote note){Note=note;} }

C# 文件 Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
public static class Program {

public static void Main() {
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var n=new DemoNote();var e=new DemoEnvelope(n);n.Text="b";Console.WriteLine(e.Note.Text);
}
}

C# 输出:

b

GDScript 示例文件 demo_note.gd:

class_name DemoNote
extends RefCounted
var text: String = "a"

GDScript 示例文件 demo_envelope.gd:

class_name DemoEnvelope
extends RefCounted
var note: DemoNote
func _init(value: DemoNote) -> void:
	note = value

GDScript 示例文件 main.gd:

extends Node

func _ready() -> void:
	var note: DemoNote = DemoNote.new()
	var envelope: DemoEnvelope = DemoEnvelope.new(note)
	note.text = "b"
	print(envelope.note.text)

GDScript 输出:

b
challenge icon

挑战

简单

实现 RateRule(cents:int),并提供 cost(units:int)。BillBox(rule:RateRule) 会存储传入的规则,total(units:int) 会委托该规则处理。之后更改 rule.cents 必须影响账单。Solve 使用 [rate,units]。

输入是 stdin 上的一个 JSON 数组。锁定的 main 会解析它,调用公开 API,并输出 result=,后接返回的文本和换行符。辅助函数不应输出内容。在处理输入用例之前,会使用独立的固定探测来验证必需的 API 行为,但不会强制规定实现风格。

你的代码写在 rate_rule.gd、bill_box.gd 和 exercise.gd 中。main.gd 包含提供的输入和输出代码,不能编辑。每个 class_name 类型都要放在对应名称的文件中。

亲手试试

extends Node

func contract_ok(data: Array) -> bool:
	var rule: RateRule = RateRule.new(2)
	var bill: BillBox = BillBox.new(rule)
	rule.cents = 7
	if rule.cost(3) != 21 or bill.total(3) != 21: return false
	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C# 开发者的 GDScript中的所有课

自己练习: GDScript 在线编译器