Delphi程序参数的默认值

时间:2017-12-13 07:52:29

标签: delphi

procedure CaseListMyShares(search: String);

我有这样的程序。以下是内容:

procedure TFormMain.CaseListMyShares(search: String);
var
  i: Integer;
begin
  myShares := obAkasShareApiAdapter.UserShares('1', search, '', '');
  MySharesGrid.RowCount:= Length(myShares) +1;
  MySharesGrid.AddCheckBoxColumn(0, false);
  MySharesGrid.AutoFitColumns;

  for i := 0 to Length(myShares) -1 do
  begin
    MySharesGrid.Cells[1, i+1]:= myShares[i].patientCase;
    MySharesGrid.Cells[2, i+1]:= myShares[i].sharedUser;
    MySharesGrid.Cells[3, i+1]:= myShares[i].creationDate;
    MySharesGrid.Cells[4, i+1]:= statusText[StrToInt(myShares[i].situation) -1];
    MySharesGrid.Cells[5, i+1]:= '';
    MySharesGrid.Cells[6, i+1]:= '';
  end;
end;

我想以两种方式调用此函数,这些方式没有任何参数和参数。我找到了overload关键字的程序,但我不想写两次相同的函数。

如果我将此程序称为CaseListMyShares('');,则可以。

但我可以在delphi中执行此操作吗?

procedure TFormMain.CaseListMyShares(search = '': String);

并致电:

CaseListMyShares();

1 个答案:

答案 0 :(得分:13)

有两种方法可以实现这一目标。这两种方法都很有用,它们通常是可以互换的。但是,有些情况下,其中一个或另一个更可取,因此值得了解以下两种技术。

默认参数值

此语法如下:

procedure DoSomething(Param: string = '');

你可以这样调用这个方法:

DoSomething();
DoSomething('');

以上两种行为都是一样的。实际上,当编译器遇到DoSomething()时,它只是替换默认参数值并编译代码,就像编写了DoSomething('')一样。

文档:Default Parameters

重载方法

procedure DoSomething(Param: string); overload;
procedure DoSomething; overload;

这些方法的实现如下:

procedure TMyClass.DoSomething(Param: string);
begin
  // implement logic of the method here
end;

procedure TMyClass.DoSomething;
begin
  DoSomething('');
end;

请注意,逻辑主体仍然只实现一次。以这种方式编写重载时,会有一个执行工作的 master 方法,以及一些调用该主方法的其他重载。

文档:Overloading Procedures and Functions

相关问题