在 Delphi 中具有多个实现的单个接口
A single interface with multiple implementations in Delphi
我可以用我使用的其他语言来做到这一点。例如,当需要创建 Web 应用程序时,我可以在 PHP 中执行此操作,但这是我想做的,但找不到解决方案:
我想定义一个接口说:
unit myBigUnit;
interface
uses someUnits;
type
TsampleType = class
someVar: Integer;
someOtherVar: Integer;
someObj: TneatObj;
procedure foo;
function bar : String;
procedure foobar(a: boolean);
所有这些都在一个文件中。现在我想要两个实现此接口或至少知道它的文件。在 php 我只能说
class blah implements thisInterface
但我在 Delphi 中找不到等效项。我想做的是在一个单元中实现它,而在另一个单元中我只是想让它知道这些 functions/procedures/et al 所以我可以从那里调用它们。我一点也不关心它是如何实现的。我认为这就是拥有接口并将它们与实现者分开的全部意义吗?
如何在 Delphi 中执行此操作?
那么你应该使用接口:
...
type
IsampleType = Interface
.....
在您的 类 中实现它:
type
TIntfType = class(TInterfacedObject, ISampleType)
....
以及您将在 Delphi...
中使用 F1 找到的详细信息
您需要使用实际的界面,例如:
type
IsampleType = interface
procedure foo;
function bar : String;
procedure foobar(a: boolean);
end;
一个interface
只能有方法和属性,不能有变量。
然后您可以根据需要在 类 中实现接口,例如:
type
TMyClass = class(TInterfacedObject, IsampleType)
public
someVar: Integer;
someOtherVar: Integer;
someObj: TneatObj;
procedure foo;
function bar : String;
procedure foobar(a: boolean);
end;
var
Sample: IsampleType;
begin
Sample := TMyClass.Create;
// use Sample as needed...
end;
Delphi 接口是引用计数的。 TInterfacedObject
为您处理引用计数。当它的引用计数下降到 0 时,它会自动释放对象。
您可以在 Delphi 的文档中找到更多详细信息:
我可以用我使用的其他语言来做到这一点。例如,当需要创建 Web 应用程序时,我可以在 PHP 中执行此操作,但这是我想做的,但找不到解决方案:
我想定义一个接口说:
unit myBigUnit;
interface
uses someUnits;
type
TsampleType = class
someVar: Integer;
someOtherVar: Integer;
someObj: TneatObj;
procedure foo;
function bar : String;
procedure foobar(a: boolean);
所有这些都在一个文件中。现在我想要两个实现此接口或至少知道它的文件。在 php 我只能说
class blah implements thisInterface
但我在 Delphi 中找不到等效项。我想做的是在一个单元中实现它,而在另一个单元中我只是想让它知道这些 functions/procedures/et al 所以我可以从那里调用它们。我一点也不关心它是如何实现的。我认为这就是拥有接口并将它们与实现者分开的全部意义吗?
如何在 Delphi 中执行此操作?
那么你应该使用接口:
...
type
IsampleType = Interface
.....
在您的 类 中实现它:
type
TIntfType = class(TInterfacedObject, ISampleType)
....
以及您将在 Delphi...
中使用 F1 找到的详细信息您需要使用实际的界面,例如:
type
IsampleType = interface
procedure foo;
function bar : String;
procedure foobar(a: boolean);
end;
一个interface
只能有方法和属性,不能有变量。
然后您可以根据需要在 类 中实现接口,例如:
type
TMyClass = class(TInterfacedObject, IsampleType)
public
someVar: Integer;
someOtherVar: Integer;
someObj: TneatObj;
procedure foo;
function bar : String;
procedure foobar(a: boolean);
end;
var
Sample: IsampleType;
begin
Sample := TMyClass.Create;
// use Sample as needed...
end;
Delphi 接口是引用计数的。 TInterfacedObject
为您处理引用计数。当它的引用计数下降到 0 时,它会自动释放对象。
您可以在 Delphi 的文档中找到更多详细信息: