如果我有这样的课程:
TServerSettings = class(TSettings)
strict private
FHTTPPort : Integer;
published
property HTTPPort : Integer read FHTTPPort write FHTTPPort default 80;
end;
如何使用RTTI获取default
属性的HTTPPort
属性?
答案 0 :(得分:3)
您可以使用TRttiInstanceProperty
类
Default
属性
{$APPTYPE CONSOLE}
{$R *.res}
uses
Rtti,
System.SysUtils;
type
TServerSettings = class
strict private
FHTTPPort : Integer;
published
property HTTPPort : Integer read FHTTPPort write FHTTPPort default 80;
end;
var
L : TRttiType;
P : TRttiProperty;
begin
try
P:= TRttiContext.Create.GetType(TServerSettings.ClassInfo).GetProperty('HTTPPort');
if P is TRttiInstanceProperty then
Writeln(TRttiInstanceProperty(P).Default);
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
答案 1 :(得分:2)
像这样:
{$APPTYPE CONSOLE}
uses
System.TypInfo;
type
TMyClass = class
strict private
FMyValue: Integer;
published
property MyValue: Integer read FMyValue default 42;
end;
var
obj: TMyClass;
PropInfo: PPropInfo;
begin
obj := TMyClass.Create;
PropInfo := GetPropInfo(obj, 'MyValue');
Writeln(PropInfo.Default);
end.
请注意,正如您所提出的那样,该课程已被打破。创建实例时,系统不会自动将属性初始化为其默认值。您需要在此类中添加构造函数才能执行此操作。