为什么GetType成功后FindType无法获取RTTI? [英] Why does FindType fail to get RTTI when GetType succeeds?
问题描述
我正在尝试使用 TRttiContext.FindType(QualifiedTypeName)
来控制对象。这是我得到的:
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.
不幸的是,似乎只有 rCtx.GetType
找到所需的类型。 (我也尝试过使用GetTypes列出所有类型。所需的类型不会出现在结果数组中。)有人知道如何强制编译器为此类型发出RTTI吗?
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?
推荐答案
您对 <$ c $的调用c> FindType 方法不会返回Rtti信息,因为此函数仅适用于公共类型
。因此,如果您检查 rType.IsPublicType
属性,返回的值为false。
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 .
必须在单元的接口部分声明公共类型(将其识别为公共)。因此,如果将 TMyClass
类定义移动到单元的接口部分,则可以毫无问题地使用 FindType
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.
这篇关于为什么GetType成功后FindType无法获取RTTI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!