From 4e035295cac73edde615ea53032c9c6129e48899 Mon Sep 17 00:00:00 2001
From: GwWuYou <95328647+GeWuYou@users.noreply.github.com>
Date: Tue, 30 Dec 2025 21:42:44 +0800
Subject: [PATCH] =?UTF-8?q?feat(core):=20=E6=B7=BB=E5=8A=A0=E5=AF=B9?=
=?UTF-8?q?=E8=B1=A1=E7=B1=BB=E5=9E=8B=E5=88=A4=E6=96=AD=E6=89=A9=E5=B1=95?=
=?UTF-8?q?=E6=96=B9=E6=B3=95?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- 实现 IfType 方法支持类型匹配时执行操作
- 添加 IfType 泛型方法支持类型匹配时返回计算结果
- 提供 As 扩展方法用于安全类型转换
- 实现 Do 方法支持链式调用操作
- 添加 SwitchType 方法支持运行时类型分派处理
- 提供类型条件判断和多分支处理功能
- 完善方法注释和使用示例文档
---
.../extensions/ObjectExtensions.cs | 186 ++++++++++++++++++
1 file changed, 186 insertions(+)
create mode 100644 GFramework.Core/extensions/ObjectExtensions.cs
diff --git a/GFramework.Core/extensions/ObjectExtensions.cs b/GFramework.Core/extensions/ObjectExtensions.cs
new file mode 100644
index 0000000..d1783a5
--- /dev/null
+++ b/GFramework.Core/extensions/ObjectExtensions.cs
@@ -0,0 +1,186 @@
+namespace GFramework.Core.extensions;
+
+///
+/// 提供基于运行时类型判断的对象扩展方法,
+/// 用于简化类型分支、链式调用和架构分派逻辑。
+///
+public static class ObjectExtensions
+{
+ ///
+ /// 当对象是指定类型 时,执行给定的操作。
+ ///
+ /// 目标类型
+ /// 源对象
+ /// 当对象类型匹配时执行的操作
+ /// 如果类型匹配并执行了操作则返回 true,否则返回 false
+ ///
+ ///
+ /// object obj = new MyRule();
+ ///
+ /// bool executed = obj.IfType<MyRule>(rule =>
+ /// {
+ /// rule.Initialize();
+ /// });
+ ///
+ ///
+ public static bool IfType(this object obj, Action action)
+ {
+ if (obj is not T target) return false;
+ action(target);
+ return true;
+ }
+
+ ///
+ /// 当对象是指定类型 时,
+ /// 使用给定函数计算并返回结果;否则返回默认值。
+ ///
+ /// 目标类型
+ /// 返回结果类型
+ /// 源对象
+ /// 当类型匹配时执行的函数
+ ///
+ /// 类型匹配时返回函数计算结果,否则返回 default
+ ///
+ ///
+ ///
+ /// object obj = new MyRule { Name = "TestRule" };
+ ///
+ /// string? name = obj.IfType<MyRule, string>(r => r.Name);
+ ///
+ ///
+ public static TResult? IfType(
+ this object obj,
+ Func func
+ )
+ where T : class
+ {
+ return obj is T target ? func(target) : default;
+ }
+
+ ///
+ /// 根据对象是否为指定类型 ,
+ /// 分别执行匹配或不匹配的操作。
+ ///
+ /// 目标类型
+ /// 源对象
+ /// 当对象类型匹配时执行的操作
+ /// 当对象类型不匹配时执行的操作
+ ///
+ ///
+ /// obj.IfType<IRule>(
+ /// rule => rule.Execute(),
+ /// other => Logger.Warn($"Unsupported type: {other.GetType()}")
+ /// );
+ ///
+ ///
+ public static void IfType(
+ this object obj,
+ Action whenMatch,
+ Action