Why does FindType fail to get RTTI when GetType succeeds?

被刻印的时光 ゝ 提交于 2019-12-23 19:36:58

问题


I'm trying to get hold of an object using TRttiContext.FindType(QualifiedTypeName). Here's what I've got:

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.

Unfortunately, only rCtx.GetType seems to find the desired type. (I've also tried to list all types using GetTypes. The desired type does not appear in the resulting array.) Anyone know how to force the compiler to emit RTTI for this type?


回答1:


Your call to the FindType method doesn't return Rtti info because this function works only for public types. So if you check the rType.IsPublicType property the value returned is false .

The public types must be declarated in the interface section of a unit (to be recognized as public). So if you move the TMyClass class definition to the interface part of a unit you will able to use the FindType without problems.



来源:https://stackoverflow.com/questions/10600186/why-does-findtype-fail-to-get-rtti-when-gettype-succeeds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!