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