我需要得到任何
TRttiType
的单位(命名空间)的名称.
到目前为止,我已尝试过以下内容.
1)使用PTypeData.UnitName,此解决方案有效,但仅当TTypeKind为tkClass时.
procedure ListAllUnits; var ctx : TRttiContext; lType: TRttiType; Units: TStrings; begin Units:=TStringList.Create; try ctx := TRttiContext.Create; for lType in ctx.GetTypes do if lType.IsInstance then //only works for classes if Units.IndexOf(UTF8ToString(GetTypeData(lType.Handle).UnitName))<0 then Units.Add(UTF8ToString(GetTypeData(lType.Handle).UnitName)); Writeln(Units.Text); finally Units.Free; end; end;
2)解析QualifiedName属性,这个解决方案到目前为止工作正常,但我对此并不满意.
procedure ListAllUnits2; function GetUnitName(lType: TRttiType): string; begin Result := StringReplace(lType.QualifiedName,'.' + lType.Name,'',[rfReplaceAll]) end; var ctx: TRttiContext; lType: TRttiType; Units: TStrings; begin Units := TStringList.Create; try ctx := TRttiContext.Create; for lType in ctx.GetTypes do if Units.IndexOf(GetUnitName(lType)) < 0 then Units.Add(GetUnitName(lType)); Writeln(Units.Text); finally Units.Free; end; end;
问题是,存在另一种可靠的方法来获取任何TRttiType的单位名称?
@H_404_14@