我正在尝试使用 D2010 RTTI 获取接口。
program rtti_sb_1;
{$APPTYPE CONSOLE}
{$M+}
uses
SysUtils,
Rtti,
mynamespace in 'mynamespace.pas';
var
ctx: TRttiContext;
RType: TRttiType;
MyClass: TMyIntfClass;
begin
ctx := TRttiContext.Create;
MyClass := TMyIntfClass.Create;
// This prints a list of all known types, including some interfaces.
// Unfortunately, IMyPrettyLittleInterface doesn't seem to be one of them.
for RType in ctx.GetTypes do
WriteLn(RType.Name);
// Finding the class implementing the interface is easy.
RType := ctx.FindType('mynamespace.TMyIntfClass');
// Finding the interface itself is not.
RType := ctx.FindType('mynamespace.IMyPrettyLittleInterface');
MyClass.Free;
ReadLn;
end.
Both IMyPrettyLittleInterface
and TMyIntfClass = class(TInterfacedObject, IMyPrettyLittleInterface)
被声明于mynamespace.pas
, 尤其
unit mynamespace;
interface
type
IMyPrettyLittleInterface = interface
['{6F89487E-5BB7-42FC-A760-38DA2329E0C5}']
end;
TMyIntfClass = class(TInterfacedObject, IMyPrettyLittleInterface)
end;
//...
有谁知道为什么这不起作用?有办法解决我的问题吗?提前致谢!
这是您发现的奇怪行为。您可以使用以下方式查找类型:
RType := ctx.GetType(TypeInfo(IMyPrettyLittleInterface));
但是,完成此操作后,您可以通过名称访问它,因此如果您需要通过名称访问它,您可以执行以下操作以使其正常工作。
示例程序:
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils,
Rtti,
TypInfo,
Unit1 in 'Unit1.pas';
var
ctx : TRttiContext;
IType : TRttiType;
begin;
ctx := TRttiContext.Create;
IType := ctx.FindType('Unit1.IExample');
if Assigned(IType) then
begin
writeln('Found');
Writeln(IType.QualifiedName);
end
else
writeln('Not Found');
ReadLn;
end.
示例单位:
unit Unit1;
interface
type
IExample = interface
['{D61F3245-13FB-44BF-A89D-BB358FAE7D19}']
end;
implementation
uses Rtti;
var
C : TRttiContext;
initialization
C.GetType(TypeInfo(IExample));
end.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)