是否可以使用新的Delphi的RTTI库从字符串中检索TypeInfo?

时间:2018-05-15 19:30:45

标签: delphi rtti typeinfo

我想知道这是否可行。我想得到TypeInfo,将类型的名称作为字符串传递。

这样的事情:

type
  TSomeValues = record
    ValueOne: Integer;
    ValueTwo: string;
  end;


function ReturnTypeInfo(aTypeName: string): TypeInfo;
begin
    // that's is the issue
end;

procedure Button1Click(Sender: TObject);
var
  _TypeInfo: TypeInfo;
begin
  _TypeInfo := ReturnTypeInfo('TSomeValues');
end;

1 个答案:

答案 0 :(得分:2)

使用TRttiContext.FindType()方法和TRttiType.Handle属性,例如:

uses
  ..., System.TypInfo, System.Rtti;

function ReturnTypeInfo(aTypeName: string): PTypeInfo;
var
  Ctx: TRttiContext;
  Typ: TRttiType;
begin
  Typ := Ctx.FindType(aTypeName);
  if Typ <> nil then
    Result := Typ.Handle
  else
    Result := nil;
end;

...

type
  TSomeValues = record
    ValueOne: Integer;
    ValueTwo: string;
  end;

procedure TForm1.Button1Click(Sender: TObject);
var
  _TypeInfo: PTypeInfo;
begin
  _TypeInfo := ReturnTypeInfo('Unit1.TSomeValues');
  ...
end;