How to get property type name for custom properties?

In Delphi 2007, I added a new line type to the project:

type
  String40 = string;

This property is used in the class:

type
  TPerson = class
  private
    FFirstName = String40;
  published
    FirstName: string40 read FFirstName write FFirstName;
  end;

At run time, I want to get the FirstName property name using RTTI. I expect this to be String40:

var
  MyPropInfo: TPropInfo;
  PropTypeName: string;
  MyPerson: TPerson;
begin
  MyPerson := TPerson.Create;
  MyPropInfo := GetPropInfo(MyPerson, 'FirstName')^;
  PropTypeName := MyPropInfo.PropType^.Name;

However, in this example, PropTypeName is "string". What do I need to do to get the correct property type name, "String40"?

+3
source share
2 answers

It works in Delphi5

type
  String40 = type string;

As for the rest of your code, in order to have RTTI, you have to

  • inherits TPerson from TPersistent or
  • use compiler directive {$ M +} for TPerson
  • publish property Firstname

:, , ?

program Project1;

uses
  Classes,
  typInfo,
  Dialogs,
  Forms;

{$R *.RES}

type
  String40 = type string;
  TPerson = class(TPersistent)
  private
    FFirstName: String40;
  published
    property FirstName: string40 read FFirstName write FFirstName;
  end;

var
  MyPropInfo: TPropInfo;
  PropTypeName: string;
  MyPerson: TPerson;

begin
  Application.Initialize;
  MyPerson := TPerson.Create;
  MyPropInfo := GetPropInfo(MyPerson, 'FirstName')^;
  PropTypeName := MyPropInfo.PropType^.Name;
  ShowMessage(PropTypeName);
end.
+11

:

  • .
  • type.

:

type
  String40 = type string;
  TPerson = class
  private
    FFirstName : String40;
  published
    property FirstName: string40 read FFirstName write FFirstName;
  end;

var
  MyPropInfo: PPropInfo;
  PropTypeName: string;
  MyPerson: TPerson;
begin
  MyPerson := TPerson.Create;
  try
    MyPerson.FirstName := 'My first name';
    MyPropInfo := GetPropInfo(MyPerson, 'FirstName');
    if MyPropInfo<>nil then begin
      PropTypeName := MyPropInfo^.PropType^.Name;
      Memo1.Lines.Add(PropTypeName);
    end;
  finally
    MyPerson.FRee;
  end;
end;

D2009.

+4

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


All Articles