我想要创建一个接口对象,它支持来自其他地方的接口+我自己的函数。那么,如何堆栈/聚合/增强接口呢?我想这是可能的,但我找不到适合我的继承实验的片段或演示。
这个解决方案并不完全符合我的要求:
TImplement = Class(TInterfacedObject, IOne, ITwo)
private
FOne: IOne;
public
property One: IOne read FOne implements IOne;
property Two: ITwo read FTwo implements ITwo;
end;当前使用情况:
(MyInterface as IOne).Something;
(MyInterface as ITwo).SomethingElse;预期用途:
MyInterface.Something;
MyInterface.SomethingElse;我尝试继承接口:
ITogether = Interface(IOne)
procedure SomeThingElse;
end:
TImplement = Class(TInterfacedObject, ITogether)
// or Class(TInterfacedObject, ITogether, IOne) => Both result in missing Implementation message on compile ...
private
FOne: IOne;
function SomeThingElse;
public
property One: IOne read FOne implements IOne;
end;这个组合表示如下:
E2291实现方法x从接口IOne缺失。
是否有可能以一种方式组合接口,使“免费”调用成为可能?
编辑:罗布·兰伯登的答案是给我缺失的信息。Uwe Raabes的答案是正确的实现。(而且可能是唯一可能的)所以uwe赢得了答案,而我只能对这个答案投反对票。
发布于 2021-09-22 15:26:47
您可以实现IOne方法并将它们转发到FOne接口。
type
IOne = interface
['{19F785C0-5D2E-479F-BB2C-88A00BA4C812}']
procedure Something;
end;
ITogether = interface(IOne)
['{B8B7F690-DC98-41AB-A6D9-29F70330EDA5}']
procedure SomethingElse;
end;
type
TTogether = class(TInterfacedObject, ITogether)
private
FOne: IOne;
protected
property One: IOne read FOne;
public
constructor Create(AOne: IOne);
procedure SomethingElse;
procedure Something;
end;
constructor TTogether.Create(AOne: IOne);
begin
inherited Create;
FOne := AOne;
end;
procedure TTogether.Something;
begin
One.Something;
end;
procedure TTogether.SomethingElse;
begin
{ Do something else }
end;AFAIK,当实现者是接口属性时,没有像implements这样的语言构造。
更新:在需要扩展IOne接口的几种情况下,您可以编写一个包装类,从而为实现关键字提供一个很好的候选。
type
TOneWrapper = class
private
FOne: IOne;
protected
property One: IOne read FOne;
public
constructor Create(AOne: IOne);
procedure Something;
end;
type
TTogether = class(TInterfacedObject, ITogether)
private
FOne: TOneWrapper;
protected
property One: TOneWrapper read FOne implements ITogether;
public
constructor Create(AOne: IOne);
destructor Destroy; override;
procedure SomethingElse;
end;
constructor TTogether.Create(AOne: IOne);
begin
inherited Create;
FOne := TOneWrapper.Create(AOne);
end;
destructor TTogether.Destroy;
begin
FOne.Free;
inherited Destroy;
end;
procedure TTogether.SomethingElse;
begin
{ Do something else }
end;
constructor TOneWrapper.Create(AOne: IOne);
begin
inherited Create;
FOne := AOne;
end;
procedure TOneWrapper.Something;
begin
One.Something;
end;发布于 2021-09-23 07:12:00
你的问题似乎是关于两件事。首先,它是关于调用方法而不必转换。
只需使用对象引用,您就可以做到这一点。
MyObject:=TImplements.Create;
MyObject.Something;
MyObject.SomethingElse;其次,它是关于实现一个接口,而不必重新实现这些功能。
根据其定义,Delphi接口不能包括实现。(方法必须是抽象的,或者用C++术语来说,它们是“纯虚拟的”)。
这意味着您不能像使用C++那样执行多继承类型实现。任何实现接口的对象都必须实现所有的实现函数.或者..。
可以像在示例中那样将接口委托给属性,如果使用对象引用,仍然可以调用这些方法而无需强制转换。
https://stackoverflow.com/questions/69286800
复制相似问题