实现方法不在公共部分是否重要?
就编译器而言。没有什么不同的。
话虽如此。私有方法仍然是私有的,即使您可以通过接口访问它们。
unit unit1;
....
IItest = interface
['{A3D5FEB6-8E29-4EA8-8DC9-7988294EFA65}']
procedure Test;
end;
TTest = class(TInterfacedObject, IItest)
private
procedure Test;
end;
unit unit2;
....
var
TestT: TTest;
TestI: ITest;
begin
TestT:= TTest.Create;
TestI:= TTest.Create;
TestT.Test; //will not compile.
TestI.Test; //works.
这样做的原因是该接口只是在其 VMT 中有一个指向方法的指针列表。接口定义中给出了方法的定义。
编译器仅检查签名是否匹配。
它不检查方法的可见性。
根据艾伦的评论,这是一个深思熟虑的设计:
将方法设为私有或受保护将确保您只能通过接口访问它们。这是一种针对对象的预期用途强制执行使用合同的方法。
请注意,这不是错误,甚至不是坏事。
属性也可以“访问”私有方法:
property Items[index: integer] read GetItem write SetItem;
这里的 GetItem 和 SetItem 通常是私有的。
这会强制您使用该属性访问项目。
使用属性时,实现方法通常受到保护(或更糟:-)。相同的逻辑适用于属性和接口。
对于接口更是如此,因为如果您混合使用接口访问和常规访问,您会遇到引用计数问题。
干净的代码
请注意,您可以在类标题中包含任意数量的可见性部分。
这样,您可以将所有接口方法放在一个部分中,将所有非接口方法放在另一个部分中。
TTest = class(TInterfacedObject, I1, I2)
//I1 methods
private
... private I1 methods here...
protected
.. more I1 methods
//I2 methods
private
.. some I2 methods
protected
..more I2 methods
//TTest methods
private
//data members
public
constructor Create;
destructor Destroy; override;
end;
这样就可以清楚地知道是什么。