【问题标题】:Delphi default value for procedure parameterDelphi 程序参数的默认值
【发布时间】:2017-12-13 07:52:28
【问题描述】:
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();

【问题讨论】:

  • 使用procedure TFormMain.CaseListMyShares(const Search: string = '');
  • @Victoria 谢谢你,为什么我们使用 const ?
  • 我建议你阅读default parametersconstant parameters主题。
  • @Victoria 像往常一样优秀。但是你为什么不再回答了?我发现坚持使用 cmets 是在浪费您的才能/经验。很明显,您仍然想提供帮助,所以为什么不回答。只是好奇:)。
  • @Nasreddine,谢谢!但我的答案只是我在 cmets 中发布的那两句话。不过,我仍在关注 FireDAC 标签。那里的许多问题需要更深入的分析,而不仅仅是重写记录的内容(这是我更喜欢的,因为当我们发现问题时,它可以使 FireDAC 比以前更好):)

标签: delphi


【解决方案1】:

有两种方法可以实现这一点。这两种方法都很有用,而且它们通常可以互换。但是,在某些情况下,一种或另一种更可取,因此值得了解以下两种技术。

默认参数值

其语法如下:

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

【讨论】:

    猜你喜欢
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 2012-08-01
    • 2011-05-07
    • 1970-01-01
    • 2011-03-25
    • 2018-06-20
    相关资源
    最近更新 更多