`overload`关键字有什么区别吗?

Wou*_*ick 11 delphi overloading

有时我在没有重载的方法后面有"overload"关键字.

除了代码的可读性和可维护性之外,这还有其他我应该注意的影响吗?

小智 18

最大的区别在于,当方法的参数不正确时,对于非重载方法,错误消息明显更好.

program Test;

procedure F(X: Integer);
begin
end;

procedure G(X: Integer); overload;
begin
end;

var
  P: Pointer = nil;

begin
  F(P); // E2010 Incompatible types: 'Integer' and 'Pointer'
  G(P); // E2250 There is no overloaded version of 'G' that can be called with these arguments
end.
Run Code Online (Sandbox Code Playgroud)

更巧妙的是,重载方法可能会超载您不知道的函数.考虑标准IfThen功能.StrUtils.IfThen只存在一次:

function IfThen(AValue: Boolean; const ATrue: string;
  AFalse: string = ''): string; overload; inline;
Run Code Online (Sandbox Code Playgroud)

但它被标记为overload.这是因为它与超载Math.IfThen,如果一个单位同时使用MathStrUtils,不合格的IfThen将解析到正确的功能取决于参数,无论在单位的顺序uses列表.

  • 很好 - 我从来不知道它可以用来解决这些问题! (3认同)