首页 > 代码库 > 依据函数名字符串执行函数

依据函数名字符串执行函数

这个问题虽然不是很严重,但却困扰本人许久。曾经多方询问朋友、查阅资料均无法达到效果。

今日偶然查到一些东西,经实测的却可行,也算了却了一桩心愿。

不再废话直接贴DEMO代码

 

 1 unit Unit2; 2  3 interface 4  5 uses 6   Vcl.Dialogs, Vcl.Forms, System.Generics.Collections, System.Variants; 7  8 type 9   TMyIntf = class(TForm)10   public11     class function PublicFunc(FuncName : string; DicIn, DicOut: TDictionary<string, Variant>): Boolean;12   published13     function Red(DicIn, DicOut: TDictionary<string, Variant>): Boolean;14     function Black(DicIn, DicOut: TDictionary<string, Variant>): Boolean;15     function Blue(DicIn, DicOut: TDictionary<string, Variant>): Boolean;16     function Green(DicIn, DicOut: TDictionary<string, Variant>): Boolean;17   end;18 19 implementation20 21 { TMyIntf }22 23 function TMyIntf.Black(DicIn, DicOut: TDictionary<string, Variant>): Boolean;24 begin25   DicOut.AddOrSetValue(Color, Black);26   Result := True;27 end;28 29 function TMyIntf.Blue(DicIn, DicOut: TDictionary<string, Variant>): Boolean;30 begin31   DicOut.AddOrSetValue(Color, Blue);32   Result := True;33 end;34 35 function TMyIntf.Green(DicIn, DicOut: TDictionary<string, Variant>): Boolean;36 begin37   DicOut.AddOrSetValue(Color, Green);38   Result := True;39 end;40 41 class function TMyIntf.PublicFunc(FuncName : string; DicIn,42   DicOut: TDictionary<string, Variant>): Boolean;43 var44   Func : function(DicIn, DicOut: TDictionary<string, Variant>): Boolean of object;45 begin46   Result := False;47   TMethod(Func).Code := TMyIntf.MethodAddress(FuncName);48   if Assigned(TMethod(Func).Code) then49     if Func(DicIn, DicOut) then50       Result := True;51 end;52 53 function TMyIntf.Red(DicIn, DicOut: TDictionary<string, Variant>): Boolean;54 begin55   DicOut.AddOrSetValue(Color, Red);56   Result := True;57 end;58 59 end.


调用非常简单,引用单元然后直接调用类函数PublicFunc即可。

此篇如若有幸被大家浏览,若您有更好的方法请不吝赐教!拜谢!

依据函数名字符串执行函数