加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

方法重载和默认参数,Delphi中的任何其他选项?

发布时间:2020-12-15 09:04:53 所属栏目:大数据 来源:网络整理
导读:我在程序中得到了一组A,B,C,D这样的数字,有时我需要计算几个数字的总和,如: function DoIt2 (a,b : Integer) : Integer ; overload begin result := a +b ; end; function DoIt3 (a,b,c : Integer) : Integer ; overload begin result := a +b +c ; end; 我
我在程序中得到了一组A,B,C,D这样的数字,有时我需要计算几个数字的总和,如:

function DoIt2 (a,b : Integer) : Integer ; overload
    begin
        result := a +b ; 
    end;


    function DoIt3 (a,b,c : Integer) : Integer ; overload
    begin
        result := a +b +c  ; 
    end;

我的问题涉及很多DoIt的功能.我无法使用,例如一个IntegerList,我需要知道什么是A和B等等…..
与无限功能重载相比,有什么好的解决方案?

解决方法

你应该使用 open array:

function Sum(const Values: array of Integer): Integer;
var
  i: Integer;
begin
  Result := 0;
  for i := low(Values) to high(Values) do
    Result := Result + Values[i];
  end;
end;

并使用open array constructor调用它:

x := Sum([1,2]);
y := Sum([1,2,3]);
z := Sum([42,666,29,1,3]);
i := Sum([x,y,z]);

等等.

事实上,你会发现这个函数(整数版本的名称为SumInt),以及许多已经在Math单元中实现的类似函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读