我正在尝试procedure of object
使用该过程通过 rtti分配一个类型的属性TRttiProperty.SetValue
,但是当我尝试进行分配时会引发此异常EInvalidCast: Invalid class typecast
此示例应用程序显示了问题
{$APPTYPE CONSOLE}
uses
Rtti,
SysUtils;
type
TMyCallBack = procedure (const Foo : string) of object;
TMyClass = class
procedure DoSomething(const Foo: String);
end;
TMyAnotherClass = class
private
FDoSomething: TMyCallBack;
published
property DoSomething : TMyCallBack read FDoSomething Write FDoSomething;
end;
{ TMyClass }
procedure TMyClass.DoSomething(const Foo: String);
begin
Writeln('Hello');
end;
Var
MyClass : TMyClass;
t : TRttiInstanceType;
v : TValue;
p : TRttiProperty;
Bar : TMyCallBack;
begin
try
MyClass:=TMyClass.Create;
try
t:=TRttiContext.Create.GetType(TMyAnotherClass).AsInstance;
v:=t.GetMethod('Create').Invoke(t.MetaclassType,[]);
p:=t.GetProperty('DoSomething');
Bar:=MyClass.DoSomething;
if p<>nil then
p.SetValue(v.AsObject, @Bar); //here the exception is raised
finally
MyClass.Free;
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
我该如何解决这个问题?