Delphi RTTI无法找到界面 [英] Delphi RTTI unable to find interface

查看:166
本文介绍了Delphi RTTI无法找到界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用D2010 RTTI获取界面。

I'm trying to fetch an interface using 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.

IMyPrettyLittleInterface TMyIntfClass = class(TInterfacedObject,IMyPrettyLittleInterface) mynamespace.pas 中声明,特别是

unit mynamespace;
interface
type
  IMyPrettyLittleInterface = interface
    ['{6F89487E-5BB7-42FC-A760-38DA2329E0C5}']
  end;
  TMyIntfClass = class(TInterfacedObject, IMyPrettyLittleInterface)
  end;
  //...

有谁知道为什么这不工作?有办法解决我的问题吗?提前致谢!

Do anyone know why this doesn't work? Is there a way to solve my problem? Thanks in advance!

推荐答案

这是一个你发现的奇怪行为。您可以使用以下方式找到该类型:

This is a strange behavior you have found. You can find the type using:

RType := ctx.GetType(TypeInfo(IMyPrettyLittleInterface));

但是,一旦你可以通过名称访问它,所以如果你需要访问它按名称,您可以执行以下操作使其正常工作。

But after you have done this once you can access it by name, so if you need to access it by Name you can do the following to make it work.

示例程序:

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无法找到界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆