很抱歉,如果这是一个noob问题(但我是Delphi noob)。
我们假设以下代码
InterfaceUnit.pas
unit InterfaceUnit;
interface
type
IMyInterface = interface(IInterface)
procedure DoStuff(withStuff : Stuff);
end;
TMyInterfaceHelperClass = class(TInterfacedObject, IMyInterface)
public
constructor Create();
destructor Destroy();
procedure DoStuff(withStuff : Stuff); virtual; abstract;
strict protected
{Have tons of standard ways how to process Stuff}
end;
implementation
{TMyInterfaceHelperClass}
constructor TMyInterfaceHelperClass.Create();
begin
inherited Create();
end;
destructor TMyInterfaceHelperClass.Destroy();
begin
inherited Destroy();
end;
{Have tons of standard ways how to process Stuff implemented here}
end.
ImplementationUnit.pas
unit ImplementationUnit;
interface
uses InterfaceUnit;
type
TMyInterfaceImplementationClass = class(TMyInterfaceHelperClass)
public
{*******************************************************************
* The Question is: ...
*******************************************************************}
constructor Create();
destructor Destroy(); override;
{*******************************************************************}
procedure DoStuff(withStuff : Stuff); override;
end;
implementation
{TMyInterfaceImplementationClass}
{*******************************************************************
* ... Why do I need to write that boilerplate code all the time?
*******************************************************************}
constructor TMyInterfaceImplementationClass.Create();
begin
inherited Create();
end;
destructor TMyInterfaceImplementationClass.Destroy();
begin
inherited Destroy();
end;
{*******************************************************************}
procedure TMyInterfaceImplementationClass.DoStuff(withStuff : Stuff);
begin
{Combine TMyInterfaceHelperClass to do extraordinary stuff with Stuff}
end;
end.
让我们跳出代码并继续使用纯文本。
由于我来自C ++背景,我想知道为什么编译器不能简单地生成上面提到的样板代码片段?
答案 0 :(得分:4)
从某种意义上说,Delphi 已经做了你想要的。只需完全省略构造函数和析构函数声明。当一个类派生自另一个类时,它会自动继承基类的构造函数和析构函数,除非你自己override
。在您的示例中,override
是多余的,可以删除。
InterfaceUnit.pas
unit InterfaceUnit;
interface
type
IMyInterface = interface(IInterface)
procedure DoStuff(withStuff : Stuff);
end;
TMyInterfaceHelperClass = class(TInterfacedObject, IMyInterface)
public
procedure DoStuff(withStuff : Stuff); virtual; abstract;
end;
implementation
{TMyInterfaceHelperClass}
end.
ImplementationUnit.pas
unit ImplementationUnit;
interface
uses InterfaceUnit;
type
TMyInterfaceImplementationClass = class(TMyInterfaceHelperClass)
public
procedure DoStuff(withStuff : Stuff); override;
end;
implementation
{TMyInterfaceImplementationClass}
procedure TMyInterfaceImplementationClass.DoStuff(withStuff : Stuff);
begin
{Combine TMyInterfaceHelperClass to do extraordinary stuff with Stuff}
end;
end.
答案 1 :(得分:0)
接口中声明的所有内容都必须由类实现。 在您的情况下,创建/销毁似乎不是必须在界面中。 Delphi中的每个类都将继承自已有Create / Destroy的TObject。
在接口中,您应该放置那些将扩展实现者类的函数。
顺便说一句,你是在一个内部创建Des()?