MrKiloByte
MrKiloByte

Reputation: 57

Field name to string in Delphi XE10 Seattle

Is there some way to get the name of a field as a string? For example, if I have a class

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

And in the procedure SomeProcedure I would like to access the name of the field fMyField, something alomg the lines of

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

Where the ShowMessage(sFieldName) would display "fMyField". Is this possible?

Upvotes: 0

Views: 710

Answers (1)

Roman Marusyk
Roman Marusyk

Reputation: 24589

You should to use Run-time type information(RTTI) in this case. TRTTIContext has a function GetFields() that returns all information about fields

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;

Upvotes: 3

Related Questions