我想創建一個支持來自其他地方的介面 我自己的函式的介面物件。那么,如何堆疊/聚合/增強介面?我想這是可能的,但我找不到特定于我的繼承實驗的片段或演示。
這個解決方案不是我想要的:
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 介面 IOne 中方法 x 的實作丟失。
是否有可能以某種方式組合介面,以便“免費”呼叫成為可能?
編輯: Rob Lambden 的回答對我來說是缺失的資訊。Uwe Raabes 答案是正確的實作。(并且可能是唯一可能的)所以 uwe 贏得了答案,我只能對 Robs 的答案投贊成票。
uj5u.com熱心網友回復:
您可以實作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介面的情況,您可以撰寫一個包裝類,該類反過來又可以很好地使用implements關鍵字。
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;
uj5u.com熱心網友回復:
你的問題似乎是關于兩件事。首先,它是關于呼叫方法而不必進行轉換。
只需使用物件參考,您就可以做到這一點。
MyObject:=TImplements.Create;
MyObject.Something;
MyObject.SomethingElse;
其次,它是關于實作介面而無需重新實作功能。
Delphi 介面,根據他們的定義,不能包括實作。(這些方法必須是抽象的,或者在 C 術語中它們是“純虛擬的”)。
這意味著您不能像使用 C 那樣執行多繼承型別實作。任何實作介面的物件都必須實作所有的實作功能……或者……
您可以像示例中一樣將介面委托給屬性,如果這樣做,如果使用物件參考,您仍然可以呼叫方法而不進行強制轉換。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315626.html
上一篇:德爾福油漆盒變色后出現故障
