【问题标题】:Delphi How to get default value for property using RTTIDelphi 如何使用 RTTI 获取属性的默认值
【发布时间】:2015-05-20 14:33:13
【问题描述】:

如果我有这样的课程:

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

如何使用 RTTI 获取 HTTPPort 属性的 default 属性?

【问题讨论】:

  • 使用旧的还是新的 RTTI ?
  • 无论在 Delphi XE3 中使用什么。版权所有 1995-2012。
  • 两者都有...只要记住我的评论,不要责怪我,当你将做的事情 更深 并且旧的 RTTI 不够用 :-)
  • 您使用的default 并不代表您认为的那样。它是一个存储说明符。它仅决定是否在设计时将属性流式传输到 DFM。 (在这种情况下,如果在流式传输 .DFM 时HTTPPort 属性为80,则不会保存HTTPPort 属性。)请参阅Storage Specifiers 部分:注意:属性值不会自动初始化为默认值。也就是说,默认指令仅在将属性值保存到表单文件时进行控制...

标签: delphi delphi-xe3 rtti


【解决方案1】:

您可以使用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.

【讨论】:

    【解决方案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.
    

    请注意,与您的问题一样,该类已损坏。创建实例时,系统不会自动将属性初始化为其默认值。你需要向这个类添加一个构造函数来做到这一点。

    【讨论】:

    • 谢谢,但如果MyValue 不是整数而是布尔值怎么办?然后我得到类似不兼容的布尔和整数类型。
    • 你必须投射它。默认属性值仅适用于序数属性。因此,对于布尔值,0 表示假,1 表示真。
    猜你喜欢
    • 2012-07-06
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 2011-06-10
    相关资源
    最近更新 更多