我最近对接口和 D2010 RTTI 进行了广泛的试验。我在运行时不知道接口的实际类型;虽然我可以使用字符串访问它的限定名称。
考虑以下:
program rtti_sb_1;
{$APPTYPE CONSOLE}
uses
SysUtils, Rtti, TypInfo, mynamespace in 'mynamespace.pas';
var
ctx: TRttiContext;
InterfaceType: TRttiType;
Method: TRttiMethod;
ActualParentInstance: IParent;
ChildInterfaceValue: TValue;
ParentInterfaceValue: TValue;
begin
ctx := TRttiContext.Create;
// Instantiation
ActualParentInstance := TChild.Create as IParent;
{$define WORKAROUND}
{$ifdef WORKAROUND}
InterfaceType := ctx.GetType(TypeInfo(IParent));
InterfaceType := ctx.GetType(TypeInfo(IChild));
{$endif}
// Fetch interface type
InterfaceType := ctx.FindType('mynamespace.IParent');
// This cast is OK and ChildMethod is executed
(ActualParentInstance as IChild).ChildMethod(100);
// Create a TValue holding the interface
TValue.Make(@ActualParentInstance, InterfaceType.Handle, ParentInterfaceValue);
InterfaceType := ctx.FindType('mynamespace.IChild');
// This cast doesn't work
if ParentInterfaceValue.TryCast(InterfaceType.Handle, ChildInterfaceValue) then begin
Method := InterfaceType.GetMethod('ChildMethod');
if (Method <> nil) then begin
Method.Invoke(ChildInterfaceValue, [100]);
end;
end;
ReadLn;
end.
内容mynamespace.pas
如下:
{$M+}
IParent = interface
['{2375F59E-D432-4D7D-8D62-768F4225FFD1}']
procedure ParentMethod(const Id: integer);
end;
{$M-}
IChild = interface(IParent)
['{6F89487E-5BB7-42FC-A760-38DA2329E0C5}']
procedure ChildMethod(const Id: integer);
end;
TParent = class(TInterfacedObject, IParent)
public
procedure ParentMethod(const Id: integer);
end;
TChild = class(TParent, IChild)
public
procedure ChildMethod(const Id: integer);
end;
为了完整起见,实现如下
procedure TParent.ParentMethod(const Id: integer);
begin
WriteLn('ParentMethod executed. Id is ' + IntToStr(Id));
end;
procedure TChild.ChildMethod(const Id: integer);
begin
WriteLn('ChildMethod executed. Id is ' + IntToStr(Id));
end;
原因{$define WORKAROUND}
可以在这篇文章中找到。
问题:有什么方法可以让我使用 RTTI 进行所需的类型转换?换句话说:有没有办法让我调用 IChild.ChildMethod,因为我知道 1)作为字符串的 IChild 的限定名称,以及 2)作为 IParent 接口对 TChild 实例的引用?(毕竟,硬编码演员工作正常。这甚至可能吗?)谢谢!