Delphi How to get default value for property using RTTI

五迷三道 提交于 2019-11-28 10:35:25

问题


If I have a class like this:

TServerSettings = class(TSettings)
strict private
    FHTTPPort : Integer;
published
    property HTTPPort : Integer read FHTTPPort write FHTTPPort default 80;
end;

How can I get the default attribute of the HTTPPort property using RTTI?


回答1:


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.




回答2:


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.


来源:https://stackoverflow.com/questions/30352756/delphi-how-to-get-default-value-for-property-using-rtti

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