【发布时间】:2012-06-06 20:24:04
【问题描述】:
当我们在 Delphi 中设计一个类时,通常我们有私有字段(成员)、私有 setter 和 getter 方法以及一个公共属性。从课堂之外,只能通过公共财产访问该数据;该类的用户甚至不知道存在 getter 方法。
所以getter和setter方法封装了实例成员,属性封装了getter和setter方法。
但是,在定义接口时,我们会公开这些方法:
ICounter = interface
// I wouldn't want to specify these 2 methods in the interface, but I'm forced to
function GetCount: Integer;
procedure SetCount(Value: Integer);
property Count: Integer read GetCount write SetCount;
end;
实现具体类:
TCounter = class(TInterfacedObject, ICounter)
private
function GetCount: Integer;
procedure SetCount(Value: Integer);
public
property Count: Integer read GetCount write SetCount;
end
使用它:
var
Counter: ICounter;
begin
Counter := TCounter.Create;
Counter.Count := 0; // Ok, that's my public property
// The access should me made by the property, not by these methods
Counter.SetCount(Counter.GetCount + 1);
end;
如果属性封装了getter/setter私有方法,这不是违规吗? getter 和 setter 是具体类的内部结构,不应暴露。
【问题讨论】:
-
这听起来像是在咆哮。你有什么问题?
-
哪一点让您感到困惑?这对我来说非常有意义。
-
-1 用于在您已经获得三个答案之后完全改变问题的性质。我反对你的说法,即我的编辑“改变了方向”。我的编辑将您的两个问题放入标题中,以便标题是一个正确的问题。 Yours 是改变方向的编辑。
-
对那个 Rob 感到抱歉,但问题不在于“为什么我不能从接口访问实例成员”,我已经知道了。问题是“接口应该公开属性封装的内部方法吗?”。文字真的很混乱,我的英语也很烂。
-
接口中的属性是一个丑陋的 hack IMO。明确定义底层方法肯定是必要的,但它错过了它们的全部意义(为了简化事情)。此外,必须在接口的每个实现上重新定义属性也是荒谬的。您最终在接口中有 2 个方法定义和 1 个属性定义,再加上类中的字段本身。单个字段的 7 个定义,以及 getter 和 setter 本身的实现。如此简单的任务需要大量的代码。
标签: delphi oop properties interface