rtti路由
rtti路由
/// <author>2023-1-26</author> unit rtti.execfunc; interface uses System.Classes, system.Rtti, System.StrUtils, System.SysUtils; type /// <code> /// 基类 /// </code> TFunc = class(TPersistent) end; /// <summary> /// 动态执行指定类的方法 /// </summary> /// <param name="className">类名</param> /// <param name="funcName">方法名</param> /// <param name="funcParam">方法参数</param> function execFunc(className, funcName: string; funcParam: array of TValue): TValue; implementation function FindAClass(const className: string): TClass; var ctx: TRttiContext; typ: TRttiType; list: TArray<TRttiType>; begin Result := nil; ctx := TRttiContext.Create; list := ctx.GetTypes; for typ in list do begin if typ.IsInstance and (EndsText(className, typ.Name)) then begin Result := typ.AsInstance.MetaClassType; break; end; end; ctx.Free; end; function execFunc(className, funcName: string; funcParam: array of TValue): TValue; begin var ctx: TRttiContext; var t: TRttiType; var m: TRttiMethod; ctx := TRttiContext.Create; var c: TClass := FindAClass(className); if c = nil then begin Writeln('还没有注册类: RegisterClass(TFunc1)'); Exit; end; t := ctx.GetType(c); m := t.GetMethod(funcName); var o: TFunc := c.Create as TFunc; Result := m.Invoke(o, funcParam); ctx.Free; o.Free; end; end.
非RTTI的:
/// <author>2023-2-10</author> fit delphi\lazarus unit api.router; {$IFDEF fpc} {$MODE DELPHI}{$H+} {$ENDIF} interface uses keyvalue.serialize, Classes, StrUtils, SysUtils; type TFun = procedure (req, res: TSerialize) of object; /// <code> /// 基类 /// </code> TFunc = class(TPersistent); /// <summary> /// 动态执行指定类的方法 /// </summary> procedure RouterAPI(className, funcName: string; req, res: TSerialize); implementation procedure RouterAPI(className, funcName: string; req, res: TSerialize); var m: TMethod; f: TFun; p: TPersistentClass; begin p := FindClass(className); if p = nil then exit; m.Data := Pointer(p); m.Code := p.MethodAddress(funcName); if Assigned(m.Code) then begin f := TFun(m); f(req, res); end; end; end.
本文来自博客园,作者:{咏南中间件},转载请注明原文链接:https://www.cnblogs.com/hnxxcxg/p/17069179.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2018-01-27 UNIGUI换版本注意事项
2015-01-27 结构体的序列和还原