Delphi程序参数的默认值

Nev*_*ore 11 delphi

procedure CaseListMyShares(search: String);
Run Code Online (Sandbox Code Playgroud)

我有这样的程序.这是内容:

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;
Run Code Online (Sandbox Code Playgroud)

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

如果我称这个程序为CaseListMyShares('');,那就有效.

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

procedure TFormMain.CaseListMyShares(search = '': String);
Run Code Online (Sandbox Code Playgroud)

并致电:

CaseListMyShares();
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 16

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

默认参数值

其语法如下:

procedure DoSomething(Param: string = '');
Run Code Online (Sandbox Code Playgroud)

您可以像这样调用方法:

DoSomething();
DoSomething('');
Run Code Online (Sandbox Code Playgroud)

以上两者都以相同的方式表现.实际上,当编译器遇到DoSomething()它时,它只是替换默认参数值并编译代码,就像编写代码一样DoSomething('').

文档:默认参数.

重载方法

procedure DoSomething(Param: string); overload;
procedure DoSomething; overload;
Run Code Online (Sandbox Code Playgroud)

这些方法将实现如下:

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

procedure TMyClass.DoSomething;
begin
  DoSomething('');
end;
Run Code Online (Sandbox Code Playgroud)

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

文档:重载过程和函数.