gpt4 book ai didi

delphi - 在Delphi中实现接口(interface)时,实现方法不在public部分有关系吗?

转载 作者:行者123 更新时间:2023-12-03 19:26:05 29 4
gpt4 key购买 nike

给定下面的界面:

ITest = interface ['guidhere']
procedure TestMethod;
end;
有什么理由拥有 TestMethod()声明为 public在实现类中?我已经把它放在了 privateprotected部分,它似乎没有什么区别。我只是想知道是否有任何准则,从设计角度(或任何角度),使 public部分正确的部分来实现该方法。

最佳答案

does it matter if the implementing methods are not in the public section?



就编译器而言。没有什么不同的。

话虽如此。私有(private)方法仍然是私有(private)的,即使您可以通过接口(interface)访问它们。
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.

这样做的原因是该接口(interface)仅在其 VMT 中有一个指向方法的指针列表。方法的定义在接口(interface)定义中给出。
编译器只检查签名是否匹配。
它不检查方法的可见性。

根据艾伦的评论,这是一个深思熟虑的设计:

Making the methods private or protected will ensure that you can only access them through the interface. This is a way to enforce a usage contract for the intended use of the object.



请注意,这不是错误,甚至不是坏事。
属性也可以“访问”私有(private)方法:
property Items[index: integer] read GetItem write SetItem;  

这里 GetItem 和 SetItem 通常是私有(private)的。
这会强制您使用该属性访问项目。
使用属性时,实现方法通常受到保护(或更糟:-)。相同的逻辑适用于属性和接口(interface)。

接口(interface)更是如此,因为如果您混合使用接口(interface)访问和常规访问,您将遇到引用计数问题。

清洁码
请注意,您可以在类标题中拥有任意数量的可见性部分。
这样,您可以将所有接口(interface)方法放在一个部分中,将所有非接口(interface)方法放在另一个部分中。
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;

这样一来,它是什么就很清楚了。

关于delphi - 在Delphi中实现接口(interface)时,实现方法不在public部分有关系吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37029987/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com