gpt4 book ai didi

Delphi RTTI无法找到接口(interface)

转载 作者:行者123 更新时间:2023-12-03 15:17:38 24 4
gpt4 key购买 nike

我正在尝试使用 D2010 RTTI 获取接口(interface)。

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.

IMyPrettyLittleInterfaceTMyIntfClass = 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.

关于Delphi RTTI无法找到接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2997761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com