Get variable name using RTTI

I am trying to get a variable name using RTTI like this.

Here is my test.

type TStringHelper = record helper for string function Name: string; end; TMyRecord = record Field1:string; end; implementation { TStringHelper } function TStringHelper.Name: string; var context : TRttiContext; begin context := TRttiContext.Create; result := context.GetType(@Self).Name; // return empty context.Free; end; procedure TForm2.FormCreate(Sender: TObject); var r : TMyRecord; begin ShowMessage(r.Field1.Name); end; 

The name of the returned TRttiType is empty.

Is there any way to get the variable name?

+6
source share
1 answer

RTTI provides information about types, not about variables. In general, there is no way using RTTI, given the address of a variable, to find its name.

Not only does RTTI not help, but what you try as a method of a string object is actually impossible. Imagine a scenario in which you have two variables related to the same object.

 S := 'foo'; T := S; 

What is the name of one string object here. Is it S or is it T?

+6
source

Source: https://habr.com/ru/post/1011932/


All Articles