在Delphi 2007中,我为我的项目添加了一个新的字符串类型:
type
String40 = string;
此属性用于类:
type
TPerson = class
private
FFirstName = String40;
published
FirstName: string40 read FFirstName write FFirstName;
end;
在运行时,我希望使用RTTI获取属性FirstName的名称。我希望它是String40:
var
MyPropInfo: TPropInfo;
PropTypeName: string;
MyPerson: TPerson;
begin
MyPerson := TPerson.Create;
MyPropInfo := GetPropInfo(MyPerson, 'FirstName')^;
PropTypeName := MyPropInfo.PropType^.Name;
但是,在此示例中,PropTypeName是'string'。我需要做什么才能获得正确的属性类型名称'String40'?
答案 0 :(得分:11)
这适用于Delphi5
type
String40 = type string;
至于你的其余代码,要使RTTI可用
编辑:如果您编译并运行这段代码会发生什么?
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.
答案 1 :(得分:4)
你需要做两件事:
然后你得到:
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中测试过。