在 Delphi 10.3.3 中使用 RTTI 收集 class 的所有后代

Collect all descendants of a class using RTTI in Delphi 10.3.3

我需要一个基础 TClass 的所有后代的 TClass。

我试过这段代码:

type
  TClassList = TList<TClass>;

class procedure TClassUtility.collectDescendantClasses( ancestorClass_ : TClass; descendantClasses_ : TClassList );
var
  ctx: TRttiContext;
  list : TArray<TRttiType>;
  typ: TRttiType;
begin
  if ( descendantClasses_ <> NIL ) then
  begin
    ctx := TRttiContext.Create;
    try
      list := ctx.GetTypes;
      for typ in list do
      begin
        if ( typ.TypeKind = tkInstance ) then
          if ( ( ancestorClass_ = NIL ) or ( typ.ClassType.InheritsFrom( ancestorClass_ ) ) ) then
            descendantClasses_.Add( typ.ClassType );
      end;
    finally
      ctx.Free
    end;
  end else
    raise Exception.Create('' );
end;

它什么也不收集。对于所有列表项,typ.ClassType.QualifiedClassName 总是 TRTTIInstanceTypetyp.QualifiedName 存储正确的类型名称。但是,如果 typ.ClassType 是记录本身,我如何访问名为 typ.QualifiedNameTClass

我无法使用 Delphi 帮助解决问题。

您需要查看 typ 是否属于类型 TRttiInstanceType and if so you can access its MetaclassType 属性:

for typ in list do
  if typ is TRttiInstanceType then
    if (ancestorClass_ = nil) or TRttiInstanceType(typ).MetaclassType.InheritsFrom(ancestorClass_) then
      descendantClasses_.Add(TRttiInstanceType(typ).MetaclassType);