Delphi How to get default value for property using RTTI

不羁岁月 提交于 2019-11-29 16:17:24

Like this:

{$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.

Note that the class as it stands, just as is so for that in your question, is broken. The system will not automatically initialise properties to their default value when an instance is created. You would need to add a constructor to this class to do that.

You can use the Default property of the TRttiInstanceProperty class

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