mirror of
https://github.com/GeWuYou/GFramework.git
synced 2026-03-24 20:34:29 +08:00
feat(GFramework.Godot): 添加 Node 扩展方法 OfType 用于类型转换
新增 OfType 扩展方法,支持将 Node 安全转换为目标类型 T。 该方法会在节点无效或类型不匹配时抛出 InvalidCastException 异常。 同时优化了 SafeCallDeferred 方法的节点有效性检查逻辑。
This commit is contained in:
parent
49383660a7
commit
be71076efc
@ -237,7 +237,25 @@ public static class NodeExtensions
|
|||||||
public static void SafeCallDeferred(this Node? node, string method)
|
public static void SafeCallDeferred(this Node? node, string method)
|
||||||
{
|
{
|
||||||
// 检查节点是否为空且实例是否有效,有效时才执行延迟调用
|
// 检查节点是否为空且实例是否有效,有效时才执行延迟调用
|
||||||
if (node != null && GodotObject.IsInstanceValid(node))
|
if (node.IsValidNode())
|
||||||
node.CallDeferred(method);
|
node!.CallDeferred(method);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 将指定节点转换为目标类型T
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T">目标节点类型,必须继承自Node</typeparam>
|
||||||
|
/// <param name="node">要转换的节点对象,可以为null</param>
|
||||||
|
/// <returns>转换后的目标类型节点</returns>
|
||||||
|
/// <exception cref="InvalidCastException">当节点无效或类型不匹配时抛出</exception>
|
||||||
|
public static T OfType<T>(this Node? node) where T : Node
|
||||||
|
{
|
||||||
|
// 检查节点是否有效且类型匹配
|
||||||
|
if (node.IsValidNode()&& node is T t)
|
||||||
|
return t;
|
||||||
|
throw new InvalidCastException($"Cannot cast {node} to {typeof(T)}");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user