【问题标题】:A single interface with multiple implementations in Delphi [closed]Delphi中具有多个实现的单个接口[关闭]
【发布时间】:2015-07-28 20:13:52
【问题描述】:

我可以用我使用的其他语言做到这一点。例如,当需要创建 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 中做到这一点?

【问题讨论】:

  • 您是否考虑过阅读有关接口的 Delphi 文档? Delphi 从 90 年代后期就开始使用它们,所以我只能假设您只是看起来不太努力。
  • 我完全同意 Rob 的观点。请注意,您的类声明没有声明接口,它声明了一个类,顾名思义。类实现接口,它们不是接口。接口声明使用-surprise,surprise-interface关键字。
  • “Delphi Interfaces”没有给你任何搜索结果?
  • 接口是在 D3 中引入的。它们在 Delphi 中所做的事情与在 Java、C# 和其他语言中所做的事情相同。我不确定它们在 PHP 中是否完全相同。但是你在这里关注的“接口”是一个单元的接口部分——还有一个“实现”部分。每个 Delphi 单元都需要两者。
  • @DavidSchwartz“每个 Delphi 单元都需要两者”在技术上并不正确 - 如果您查看下面的答案,我很确定这不是 OP 所说的。

标签: delphi delphi-xe8


【解决方案1】:

你需要使用一个实际的接口,例如:

 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

【讨论】:

  • 感谢您为我更清楚地解释了这一点。 J.. 上面提到的事实是 Pascal 两次使用该关键字来表示两种不同的含义。
【解决方案2】:

那么你应该使用一个接口:

...

 type
   IsampleType = Interface
   ..... 

在你的类中实现这个:

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

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

【讨论】:

  • F1 可能无法在 Delphi XE8 中产生您所期望的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-18
  • 2019-10-12
  • 2013-07-03
  • 1970-01-01
  • 2012-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多