引用的生命周期
Coddy 面向 C# 开发者的 GDScript 课程的第 40 课,共 48 课。
普通 .NET 对象使用追踪式垃圾回收;C# using 和 IDisposable 用于清理资源,而不是强制回收。Godot RefCounted 对象使用引用计数,不会自动回收强引用循环。WeakRef 可以观察目标对象,但不会保留它。清除一个引用不会销毁仍被其他引用持有的对象。节点的生命周期与 RefCounted 数据的生命周期彼此独立。这些数据对象不需要手动释放。C# 示例使用 KeepAlive,确保在观察弱引用期间强引用仍然有效。
完成 C# 对比。将列出的所有 C# 文件一起编译;Program.Main 是入口点。
C# 文件 DemoItem.cs:
public class DemoItem {}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 a=new DemoItem();var weak=new WeakReference(a);var b=a;a=null;Console.WriteLine(Object.ReferenceEquals(weak.Target,b));GC.KeepAlive(b);
}
}C# 输出:
TrueGDScript 示例文件 main.gd:
extends Node
func _ready() -> void:
var a: RefCounted = RefCounted.new()
var weak: WeakRef = weakref(a)
var b: RefCounted = a
a = null
print(weak.get_ref() == b)GDScript 输出:
true挑战
简单实现 OwnedNote(text:String) 和静态方法 NoteViews.label(note:OwnedNote)->String。note 为 null 时返回 missing;否则返回 note.text。对于字符串输入,Solve 会创建一个 note;否则传入 null。不要手动释放 RefCounted 实例。
输入是 stdin 上的一个 JSON 数组。锁定的 main 会解析它,调用公共 API,并打印 result=,后接返回的文本和一个换行符。任何辅助函数都不应打印内容。输入用例之前会运行独立的固定探测,以验证必需的 API 行为;这些探测不会限制实现风格。
你的代码写在 owned_note.gd、note_views.gd 和 exercise.gd 中。main.gd 中包含提供的输入/输出代码,不能编辑。每个 class_name 类型都要放在对应名称的文件中。
亲手试试
extends Node
func contract_ok(data: Array) -> bool:
var original: OwnedNote = OwnedNote.new("a")
var alias: OwnedNote = original
original = null
if NoteViews.label(alias) != "a" or NoteViews.label(null) != "missing": 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))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 GDScript中的所有课
自己练习: GDScript 在线编译器