Delphi中具有多个实现的单个接口

时间:2015-07-28 20:13:52

标签: delphi delphi-xe8

我可以使用其他语言执行此操作。例如,我可以在创建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中找不到相同的东西。我想要做的是在一个单元中实现它,而在另一个单元中我只是想让它知道这些函数/过程/等等,所以我可以从那里调用它们。我不太关心它是如何实现的。我认为这是接口并将它们与实现者分开的重点?

如何在Delphi中执行此操作?

2 个答案:

答案 0 :(得分:5)

您需要使用实际界面,例如:

 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的文档中找到更多详细信息:

Object Interfaces Index

答案 1 :(得分:3)

然后你应该使用一个接口:

...

 type
   IsampleType = Interface
   ..... 

在你的课程中实现这个:

type
  TIntfType = class(TInterfacedObject, ISampleType)
  ....

以及您在Delphi中使用F1找到的详细信息...

相关问题