我想将 TRttiMethod
作为匿名方法处理。我怎么能这样做?
以下是我希望工作方式的简化示例:
接口:
TMyClass = class
public
// this method will be acquired via Rtti
procedure Foo;
// this method shall return above Foo as anonymous method
function GetMethodAsAnonymous: TProc;
end;
实现:
function TMyClass.GetMethodAsAnonymous: TProc;
var
Ctx: TRttiContext;
RttiType: TRttiType;
RttiMethod: TRttiMethod;
begin
Ctx := TRttiContext.Create;
try
RttiType := Ctx.GetType(Self.ClassType);
RttiMethod := RttiType.GetMethod('Foo');
Result := ??????; // <-- I want to put RttiMethod here - but how?
finally
Ctx.Free;
end;
end;
答案 0 :(得分:2)
如果你真的想要一个匿名方法,那就制作一个匿名方法:
Result := procedure
begin
RttiMethod.Invoke(Self, []);
end;
您还可以构造一个简单的方法指针:
var
Method: procedure of object;
TMethod(Method).Code := RttiMethod.CodeAddress;
TMethod(Method).Data := Self;
Result := Method;
最直接的方法当然不使用RTTI:
Result := Foo;