Delphi组件自定义属性不保存在DFM文件中

问题描述

我在自定义组件上有一个属性,我不想保存在DFM文件中。我已经重写了DefineProperties方法,以不提供ReadData和WriteData过程,期望它不会保存其值,但仍然可以。

procedure TAEFDQuery.DefineProperties(Filer: TFiler);
begin
  inherited;
  // Set the ADO Compatibility custom properties to not be saved on the DFM
  Filer.DefineProperty('CommandText',nil,False);
end;

不保存该属性的原因是因为我已经将一个项目从ADO移植到FireDAC,并且创建了“伪”属性,该属性使某些ADO代码可以不变地运行,并将其重定向到其对应的FireDAC属性

type
    TAEFDQuery = class(TFDQuery)
    private
        function GetCommandText: string;
        procedure SetCommandText(AValue: string);
    protected
        procedure DefineProperties(Filer: TFiler); override;
    published
        property CommandText: integer read GetCommandText write SetCommandText;
    end;

implementation

procedure TAEFDQuery.SetCommandText(AValue: string);
begin
  sql.Text := AValue;
end;

function TAEFDQuery.GetCommandText: string;
begin
  Result := sql.Text;
end;

procedure TAEFDQuery.DefineProperties(Filer: TFiler);
begin
  inherited;
  // Set the ADO Compatibility custom properties to not be saved on the DFM
  Filer.DefineProperty('CommandText',False);
end;

为了兼容性起见,如何正确地保留这些“伪”属性,而又不让它们用无用的真实属性副本填充DFM文件呢?

谢谢。

解决方法

将存储说明符添加到为或返回false的属性。

 property CommandTimeout: integer read GetCommandTimeout write SetCommandTimeout stored False;

ref:Properties (Delphi) -> Storage Specifiers

,

防止将该属性保存到DFM的另一种方法是,只需将属性声明为public而不是published,因为只有published个属性流进/出一个。 DFM。

type
  TAEFDQuery = class(TFDQuery)
  private
    function GetCommandText: string;
    procedure SetCommandText(AValue: string);
  public
    property CommandText: integer read GetCommandText write SetCommandText;
  end;

如果无法保存,则在设计时将published属性公开给对象检查器是没有意义的。如果您只是尝试移植一些旧代码,则不需要为旧属性添加设计时支持。


话虽如此,出于移植旧代码的目的,请考虑使用class helper而不是派生完整的组件,例如:

unit MyFDQueryHelper;

interface

uses
  FireDAC.Comp.Client;

type
  TAEFDQuery = class helper for TFDQuery
  private
    function GetCommandText: string;
    procedure SetCommandText(AValue: string);
  public
    property CommandText: integer read GetCommandText write SetCommandText;
  end;

implementation

procedure TAEFDQuery.SetCommandText(AValue: string);
begin
  Self.SQL.Text := AValue;
end;

function TAEFDQuery.GetCommandText: string;
begin
  Result := Self.SQL.Text;
end;

end.

现在,您只需将MyFDQueryHelper添加到单元的uses子句中,该单元中的任何TFDQuery对象将自动获得新的CommandText属性。无需将TFDQuery对象替换为TAEFDQuery对象。