当GetType成功时,为什么FindType无法获得RTTI?

con*_*tor 3 delphi rtti delphi-xe2

我正试图抓住一个物体TRttiContext.FindType(QualifiedTypeName).这是我得到的:

program MissingRTTI;
{$APPTYPE CONSOLE}
uses System.SysUtils, RTTI, Classes;
type
  TMyClass = class(TObject) end;
var
  rCtx:   TRttiContext;
  rType:  TRttiInstanceType;
begin
  rCtx := TRttiContext.Create();
  rType := rCtx.GetType(TypeInfo(TMyClass)) as TRttiInstanceType;
  if (rType <> nil) then begin
    WriteLn('Type found using TypeInfo');
  end;
  rType := rCtx.FindType(TMyClass.QualifiedClassName) as TRttiInstanceType;
  if (rType <> nil) then begin
    WriteLn('Type found using qualified class name.');
  end;
  ReadLn;
  rCtx.Free();
end.
Run Code Online (Sandbox Code Playgroud)

不幸的是,rCtx.GetType似乎只找到了所需的类型.(我也尝试使用GetTypes列出所有类型.所需的类型不会出现在结果数组中.)任何人都知道如何强制编译器为此类型发出RTTI?

RRU*_*RUZ 7

您对该FindType方法的调用不会返回Rtti信息,因为此函数 works only for public types.因此,如果您检查rType.IsPublicType属性,则返回的值为false.

公共类型必须在单元的接口部分声明(被识别为公共).因此,如果将TMyClass类定义移动到单元的接口部分,您将能够使用FindType没有问题.