Je dois obtenir le nom de l'unité (espace de nom) de TRttiType
. Jusqu'ici, j'ai essayé ce qui suit:Obtenir le nom de l'unité qui appartient à un type (TRttiType)
1) en utilisant le PTypeData.UnitName
, cette solution fonctionne, mais seulement lorsque TTypeKind est 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) Parsing la propriété QualifiedName
, cette solution fonctionne bien jusqu'à maintenant, mais je ne suis pas très heureux avec elle.
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;
la question est, existe une autre façon fiable pour obtenir le nom de l'unité de tout TRttiType
?