delphi 如何返回一个函数/方法变量?

7y4bm7vi  于 2023-04-11  发布在  其他
关注(0)|答案(1)|浏览(144)

如果我想为一个方法变量创建一个getter访问器,getter不会给予变量,但它会执行变量引用的代码。

unit Unit5;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TMyFactory1 = function : TObject of object;
  TMyFactory2 = reference to function : TObject;

  TForm5 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    fMyFactory1 : TMyFactory1;
    fMyFactory2 : TMyFactory2;
  public
    { Public declarations }
    function getMyFactory1 : TMyFactory1;
    function getMyFactory2 : TMyFactory2;
  end;

var
  Form5: TForm5;

implementation

{$R *.dfm}

function TForm5.getMyFactory1 : TMyFactory1;
begin
  result := fMyFactory1;
end;

function TForm5.getMyFactory2 : TMyFactory2;
begin
  result := fMyFactory2;
end;

procedure TForm5.Button1Click(Sender: TObject);
var
  aMF1 : TMyFactory1;
  aMF2 : TMyFactory2;
begin
  aMF1 := getMyFactory1; // Incompatible types: 'TObject' and 'TMyFactory1'
  aMF2 := getMyFactory2; // Incompatible types: 'TMyFactory2' and 'Procedure of object'
end;

end.

我可以为这个类型创建一个setter,但是我不能创建一个getter。我该如何创建它?

5fjcxozz

5fjcxozz1#

只需在函数调用的末尾添加括号。通过这种方式,您可以通知编译器您希望将函数存储在变量中。否则,您将执行函数并将其结果赋给变量。

var
  aMF1 : TMyFactory1;
  aMF2 : TMyFactory2;
begin
  aMF1 := getMyFactory1();
  aMF2 := getMyFactory2();
end;

相关问题