How to get the property type name for custom properties?

与世无争的帅哥 提交于 2019-12-21 20:28:54

问题


In Delphi 2007, I added a new string type to my project:

type
  String40 = string;

This property is used in a class:

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

During runtime, I want to get the name of the property FirstName by using RTTI. I expect it 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 get the correct property type name, 'String40'?


回答1:


This works in Delphi5

type
  String40 = type string;

As for the rest of your code, to have RTTI available you should

  • inherit TPerson from TPersistent or
  • use the {$M+} compiler directive for TPerson
  • make the Firstname property published

Edit: what happens if you compile and run this piece of code?

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.



回答2:


You need to do two things:

  1. Make the property published.
  2. Use the type keyword.

You then get:

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;

Tested in D2009.



来源:https://stackoverflow.com/questions/777125/how-to-get-the-property-type-name-for-custom-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!