From be71076efc0a82bdb6520f6e397f037a0df560cd Mon Sep 17 00:00:00 2001 From: GwWuYou <95328647+GeWuYou@users.noreply.github.com> Date: Mon, 22 Dec 2025 22:31:06 +0800 Subject: [PATCH] =?UTF-8?q?feat(GFramework.Godot):=20=E6=B7=BB=E5=8A=A0=20?= =?UTF-8?q?Node=20=E6=89=A9=E5=B1=95=E6=96=B9=E6=B3=95=20OfType=20?= =?UTF-8?q?=E7=94=A8=E4=BA=8E=E7=B1=BB=E5=9E=8B=E8=BD=AC=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 OfType 扩展方法,支持将 Node 安全转换为目标类型 T。 该方法会在节点无效或类型不匹配时抛出 InvalidCastException 异常。 同时优化了 SafeCallDeferred 方法的节点有效性检查逻辑。 --- GFramework.Godot/extensions/NodeExtensions.cs | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/GFramework.Godot/extensions/NodeExtensions.cs b/GFramework.Godot/extensions/NodeExtensions.cs index c316b5d..13737d9 100644 --- a/GFramework.Godot/extensions/NodeExtensions.cs +++ b/GFramework.Godot/extensions/NodeExtensions.cs @@ -237,7 +237,25 @@ public static class NodeExtensions public static void SafeCallDeferred(this Node? node, string method) { // 检查节点是否为空且实例是否有效,有效时才执行延迟调用 - if (node != null && GodotObject.IsInstanceValid(node)) - node.CallDeferred(method); + if (node.IsValidNode()) + node!.CallDeferred(method); } + + + /// + /// 将指定节点转换为目标类型T + /// + /// 目标节点类型,必须继承自Node + /// 要转换的节点对象,可以为null + /// 转换后的目标类型节点 + /// 当节点无效或类型不匹配时抛出 + public static T OfType(this Node? node) where T : Node + { + // 检查节点是否有效且类型匹配 + if (node.IsValidNode()&& node is T t) + return t; + throw new InvalidCastException($"Cannot cast {node} to {typeof(T)}"); + } + + } \ No newline at end of file