Delphi - 使用带有属性设置器的函数

use*_*073 2 delphi setter properties

Delphi RIO - 定义了一个名为 TBizObj 的类。属性之一与 DUNS 编号有关。DUNS 数字有时会在左侧填充“0”,正好是 9 个字符长,所以我有一个名为 SiteDUNS9 的属性(基于 fSiteDUNS9)。调用程序设置 SiteDUNS9 属性,但调用者不必担心 DUNS 是否为 9 个字符,我将在 getter/setter 属性中处理它。

当我定义我的属性来调用这个函数时,我收到一个错误“不兼容的类型”。一切都是字符串......不涉及其他类型。这是代码的相关部分:

type
  TBizObj = class(TObject)   
  private
  ...
  fSiteDUNS9:  string;
  ... 

  function FixDunsLength9(DUNS:string) :string;

  published
  ...
  property SiteDUNS9:  string read fSiteDUNS9 write FixDunsLength9;  

  end; // End of the tBizObj Class;

implementation
...  
function TBizObj.FixDunsLength9(DUNS:string):string;
begin
  //  This is a setter function for the DUNS9 routine
  result := glib_LeftPad(DUNS, 9, '0');
end;
Run Code Online (Sandbox Code Playgroud)

我已经按照 Emaracadero 网站上的示例进行操作,但仍然无法确定我做错了什么。 http://docwiki.embarcadero.com/RADStudio/Rio/en/Properties_(Delphi)

如果我将我的属性定义更改为

 property SiteDUNS9:  string read fSiteDUNS9 write fSiteDUNS9;
Run Code Online (Sandbox Code Playgroud)

然后我的程序编译正确。

Rem*_*eau 8

对于属性设置器,您需要使用 aprocedure而不是 a function。如果您需要将其用于其他目的,我将保留现有函数,并为 setter 定义一个单独的过程:

type
  TBizObj = class(TObject)
  private
    ...
    fSiteDUNS9: string;
    ...
    function FixDunsLength9(const DUNS: string): string;
    procedure SetSiteDUNS9(const Value: string);
  published
    ...
    property SiteDUNS9: string read fSiteDUNS9 write SetSiteDUNS9;
  end;
  // End of the tBizObj Class;

implementation

...

function TBizObj.FixDunsLength9(const DUNS: string): string;
begin
  Result := glib_LeftPad(DUNS, 9, '0');
end;

procedure TBizObj.SetSiteDUNS9(const Value: string);
var
  NewValue: string;
begin
  NewValue := FixDunsLength9(Value);
  if fSiteDUNS9 <> NewValue then
  begin
    fSiteDUNS9 := NewValue;
    ...
  end;
end;
Run Code Online (Sandbox Code Playgroud)


TLa*_*ama 7

您需要为 setter 方法声明一个过程。正如Property Access帮助所说:

字段或方法

写入说明符中,如果 fieldOrMethod 是方法,则它必须是一个过程,该过程采用与属性相同类型的单个值或const参数(或多个,如果它是数组属性或索引属性)。

在你的情况下,你可以像这样编写一个 setter:

type
  TBizObj = class(TObject)   
  private
    FSiteDUNS9: string;
    procedure FixDunsLength9(const DUNS: string);
  published
    property SiteDUNS9: string read FSiteDUNS9 write FixDunsLength9;
  end;

implementation

procedure TBizObj.FixDunsLength9(const DUNS: string);
begin
  if DUNS <> FSiteDUNS9 then
  begin
    DoSomeExtraStuff;
    FSiteDUNS9 := DUNS;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

但是按照命名约定,我建议您将 setter 命名为 likeSetSiteDUNS9和参数 call Value