Delphi如何使用RTTI获取属性的默认值 [英] Delphi How to get default value for property using RTTI

查看:440
本文介绍了Delphi如何使用RTTI获取属性的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的类:

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

如何获取默认值属性使用RTTI的 HTTPPort 属性

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

推荐答案

像这样:

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

这篇关于Delphi如何使用RTTI获取属性的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆