using System; 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? whenNotMatch ) where T : class { if (obj is T target) whenMatch(target); else whenNotMatch?.Invoke(obj); } /// /// 当对象是指定类型 且满足给定条件时, /// 执行指定操作。 /// /// 目标类型 /// 源对象 /// 对目标类型对象的条件判断 /// 当条件满足时执行的操作 /// 如果类型和条件均匹配并执行了操作则返回 true,否则返回 false /// /// /// obj.IfType<MyRule>( /// r => r.Enabled, /// r => r.Execute() /// ); /// /// public static bool IfType( this object obj, Func predicate, Action action ) where T : class { if (obj is not T target || !predicate(target)) return false; action(target); return true; } /// /// 尝试将对象转换为指定的引用类型 。 /// /// 目标引用类型 /// 源对象 /// /// 如果类型匹配则返回转换后的对象,否则返回 null /// /// /// /// obj.As<MyRule>() /// ?.Execute(); /// /// public static T? As(this object obj) where T : class { return obj as T; } /// /// 对对象执行指定操作后返回对象本身, /// 用于构建流式(链式)调用。 /// /// 对象类型 /// 源对象 /// 要执行的操作 /// 原对象 /// /// /// obj.As<MyRule>() /// ?.Do(r => r.Initialize()) /// ?.Do(r => r.Execute()); /// /// public static T Do(this T obj, Action action) { action(obj); return obj; } /// /// 根据对象的运行时类型,依次匹配并执行对应的处理逻辑, /// 只会执行第一个匹配成功的处理器。 /// /// 源对象 /// /// 类型与处理操作的元组数组,用于定义类型分派规则 /// /// /// /// obj.SwitchType( /// (typeof(IRule), o => HandleRule((IRule)o)), /// (typeof(ISystem), o => HandleSystem((ISystem)o)) /// ); /// /// public static void SwitchType( this object obj, params (Type type, Action action)[] handlers ) { foreach (var (type, action) in handlers) { if (!type.IsInstanceOfType(obj)) continue; action(obj); return; } } }