Delphi 我可以使用虚拟抽象方法来继承接口对象吗?
我有一个接口和一个对应的对象。例如Delphi 我可以使用虚拟抽象方法来继承接口对象吗?,delphi,inheritance,interface,Delphi,Inheritance,Interface,我有一个接口和一个对应的对象。例如 IMyInterface = interface function GetSomething: WideString; procedure SetSomething(const Value: WideString); property Something: WideString read GetSomething write SetSomething end; TMyObject = class(TInterfacedOb
IMyInterface = interface
function GetSomething: WideString;
procedure SetSomething(const Value: WideString);
property Something: WideString read GetSomething write SetSomething
end;
TMyObject = class(TInterfacedObject, IMyInterface)
private
function GetSomething: WideString;
procedure SetSomething(const Value: WideString);
public
property Something: WideString read GetSomething write SetSomething
end;
我使用此接口可以通过DLL与此对象交互
现在我想继承这个对象并重写其中的一些方法
TMyOtherObject = class(TMyObject)
private
function GetSomething: WideString; override;
procedure SetSomething(const Value: WideString); override;
除了我想让基本字段虚拟化和抽象化,基本上强迫孩子继承这些
TMyObject = class(TInterfacedObject, IMyInterface)
private
function GetSomething: WideString; virtual; abstract;
procedure SetSomething(const Value: WideString); virtual; abstract;
我可以这样做,并让界面仍然与这些字段一起工作吗?我是否也需要在接口中以这种方式定义它?(我当然知道界面中的所有字段都是抽象的)您确实可以这样做。可以使用抽象或其他虚拟方法来满足接口契约 不能将接口方法声明为
virtual
或abstract
。无论如何,这没有什么意义,因为virtual
和abstract
是实现的属性,而不是接口
最后,您不需要在实现对象中再次声明属性。因为我希望您只能通过接口引用这些对象,所以重复属性声明没有什么意义
下面是一个简单的程序来证明这一点:
{$APPTYPE CONSOLE}
type
IMyInterface = interface
procedure Foo;
end;
TMyObject = class(TInterfacedObject, IMyInterface)
private
procedure Foo; virtual; abstract;
end;
TMyOtherObject = class(TMyObject)
private
procedure Foo; override;
end;
procedure TMyOtherObject.Foo;
begin
Writeln(ClassName);
end;
var
Intf: IMyInterface;
begin
Intf := TMyOtherObject.Create;
Intf.Foo;
Readln;
end.
你确实可以做到这一点。可以使用抽象或其他虚拟方法来满足接口契约 不能将接口方法声明为
virtual
或abstract
。无论如何,这没有什么意义,因为virtual
和abstract
是实现的属性,而不是接口
最后,您不需要在实现对象中再次声明属性。因为我希望您只能通过接口引用这些对象,所以重复属性声明没有什么意义
下面是一个简单的程序来证明这一点:
{$APPTYPE CONSOLE}
type
IMyInterface = interface
procedure Foo;
end;
TMyObject = class(TInterfacedObject, IMyInterface)
private
procedure Foo; virtual; abstract;
end;
TMyOtherObject = class(TMyObject)
private
procedure Foo; override;
end;
procedure TMyOtherObject.Foo;
begin
Writeln(ClassName);
end;
var
Intf: IMyInterface;
begin
Intf := TMyOtherObject.Create;
Intf.Foo;
Readln;
end.
因此,只需像在接口中一样声明它,甚至不要在基本接口对象中实现它,而让派生对象来实现它?您只需要在接口中声明属性。这就是全部。这是因为您只能通过接口访问对象。有意义的是,此基础对象的任何继承都需要重写它。但是知道我可以在接口对象中使用虚拟抽象方法还是很好的。我因为没有更早地了解接口而给自己一记耳光…所以只需在接口中声明它就像正常的一样,甚至不要在基本接口对象中实现它,然后让派生对象来实现它?您只需要在接口中声明属性。这就是全部。这是因为您只能通过接口访问对象。有意义的是,此基础对象的任何继承都需要重写它。但知道我可以在接口对象中使用虚拟抽象方法还是很好的。我因为没有更早地了解接口而给自己一记耳光……为什么不自己在编译器中尝试呢?(边做边学)-为什么您认为这不起作用?为什么不自己在编译器中尝试?(边做边学)-为什么你认为这不起作用?