有时我在未重载的方法之后有“重载”关键字。
除了代码的可读性和可维护性之外,这是否还有我应该注意的其他影响?
最大的区别在于,当方法的参数不正确时,错误消息对于非重载方法要好得多。
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.
更微妙的是,重载的方法可能会被你不知道的函数重载。考虑标准IfThen
函数。StrUtils.IfThen
只存在一次:
function IfThen(AValue: Boolean; const ATrue: string;
AFalse: string = ''): string; overload; inline;
但它被标记为overload
。这是因为它被 重载了Math.IfThen
,并且如果单个单元同时使用Math
and StrUtils
,则不合格的IfThen
将根据参数解析为正确的函数,而不管uses
列表中单元的顺序如何。