比如我有一些函数(过程),我需要掉用他们,能不能通过函数名字符串来调用?有点儿象宏替换的意思!
以下的只能对于过程或不带参数的函数,如果函数带了参数就不能实现了,谁能解决??
type
{$M+}
TMyObj = class
published
function CommandOne: Integer;
// function CommandEx(i:integer): Integer; 这个带了参数就会出现错误
end;
{$M-}
function DoCommand1(const Command: string): Integer;
var
CommandProc: function: Integer of object;
begin
TMethod(CommandProc).Code := TMyObj.MethodAddress(Command);
if Assigned(TMethod(CommandProc).Code) then Result := CommandProc;
end;
function TMyObj.CommandOne: Integer;
begin
result:=1;
end;
{function TMyObj.CommandEx(i:integer): Integer;
begin
result:=i;
end;}
procedure TForm1.Button2Click(Sender: TObject);
begin
DoCommand1('CommandOne');
//DoCommand1('CommandEx(9)'); 这个就会出错
end;
--
WBR, LVT.
PS: A second method by V.Titov :
uses
TypInfo;
type
TCommand = (CommandOne, CommandTwo, CommandThree, CommandFour);
function DoCommand2(const Command: string): Integer;
begin
Result := 0;
case TCommand(GetEnumValue(TypeInfo(TCommand), Command)) of
CommandOne: ..;
CommandTwo: ..;
CommandThree: ..;
CommandFour: ..;
end;
end;
*******************
回复人: chinalian(连长) ( ) 信誉:100 2002-4-20 14:08:16 得分:0
函数指针:
TVisitedEvent = function(FID: integer):integer of object;
你增加如下
function DoCommand2(const Command: string;id: integer): Integer;
var
CommandProc: function(id: interger): Integer of object;
begin
TMethod(CommandProc).Code := TMyObj.MethodAddress(Command);
if Assigned(TMethod(CommandProc).Code) then Result := CommandProc(id); //注意参数
end;
应该就可以调用带参数的。
本文探讨了如何通过函数名字符串实现动态调用,并提供了两种方法:使用函数指针和枚举类型配合反射技术。同时,针对带参数的函数调用进行了特别讨论。

2万+

被折叠的 条评论
为什么被折叠?



