Delphi XE10 西雅图中字符串的字段名称

Field name to string in Delphi XE10 Seattle

有什么方法可以将字段名称作为字符串获取吗?例如,如果我有一个 class

type
 TMyClass = Class
  private 
    fMyField:string
  published
    procedure SomeProcedure
end;

在程序 SomeProcedure 中,我想访问字段的名称 fMyField,其中包含

的行
procedure TMyClass.SomeProcedure;
var
sFieldName:string;
begin
  sFieldName := fMyField.FieldName;
  ShowMessage(sFieldName)
end;

ShowMessage(sFieldName) 将显示 "fMyField"。这可能吗?

您应该使用 Run-time type information(RTTI) in this case. TRTTIContext has a function GetFields() returns 所有关于字段的信息

uses System.Rtti;

procedure TMyClass.SomeProcedure;
var 
  LRttiContext: TRTTIContext;
  LRttiType: TRttiType;
  LRttiField: TRttiField;
begin
  LRttiType := LRttiContext.GetType(TMyClass);
  for LRttiField in LRttiType.GetFields do
  begin
    if LRttiField.Parent = LRttiType  then    
      ShowMessage(LRttiField.Name);
  end;
end;