【问题标题】:I can't compile class with an interface我无法用接口编译类
【发布时间】:2015-08-15 15:30:01
【问题描述】:

我正在尝试创建一个实现接口的类,但出现以下错误:

[dcc32 Error] dl_tPA_MailJournal.pas(10): E2291 Missing implementation of interface method IInterface.QueryInterface
[dcc32 Error] dl_tPA_MailJournal.pas(10): E2291 Missing implementation of interface method IInterface._AddRef
[dcc32 Error] dl_tPA_MailJournal.pas(10): E2291 Missing implementation of interface method IInterface._Release
[dcc32 Fatal Error] MainUnit.pas(8): F2063 Could not compile used unit 'dl_tPA_MailJournal.pas'

代码是:

unit dl_tPA_MailJournal;

interface

uses
  Windows,
  Generics.Collections,
  SysUtils,
  uInterfaces;

type
  TtPA_MailJournal = class(TObject, ITable)
  public
    function GetanQId: integer;
    procedure SetanQId(const Value: integer);
    function GetadDate: TDateTime;
    procedure SetadDate(const Value: TDateTime);

    function toList: TList<string>;

    constructor Create(aId : Integer; aDate : TDateTime);

  private
    property anQId : integer read GetanQId write SetanQId;
    property adDate : TDateTime read GetadDate write SetadDate;
end;

implementation

{ TtPA_MailJournal }

constructor TtPA_MailJournal.Create(aId : Integer; aDate : TDateTime);
begin
  SetanQId(aId);
  SetadDate(aDate);
end;

function TtPA_MailJournal.GetadDate: TDateTime;
begin
  Result := adDate;
end;

function TtPA_MailJournal.GetanQId: integer;
begin
  Result := anQId ;
end;

procedure TtPA_MailJournal.SetadDate(const Value: TDateTime);
begin
  adDate := Value;
end;

procedure TtPA_MailJournal.SetanQId(const Value: integer);
begin
  anQId := Value;
end;

function TtPA_MailJournal.toList: TList<string>;
var
  aListTable: TList<TtPA_MailJournal>;
  aTable: TtPA_MailJournal;
  aListString: TList<String>;
begin
  aTable.Create(1,now);
  aListTable.Add(aTable);
  aTable.Create(2,now);
  aListTable.Add(aTable);
  aListString.Add(aListTable.ToString);

  Result := aListString;
end;

end.

界面是:

unit uInterfaces;

interface

uses
  Generics.Collections;

type
  ITable = Interface
    ['{6CED8DCE-9CC7-491F-8D93-996BE8E4D388}']
    function toList: TList<string>;
  end;

implementation

end.

【问题讨论】:

    标签: delphi interface


    【解决方案1】:

    问题是您使用TObject 作为您班级的父级。您应该改用TInterfacedObject

    在Delphi中,每个接口都继承自IInterface,因此至少有以下3 methods

    您必须实现这 3 个方法,要么自己实现它们,要么从包含这些方法的基础对象继承。

    因为你继承自TObject,但是你没有实现这3个方法,你会得到一个编译错误。如果您阅读编译器错误,您会发现它实际上为您说明了这个遗漏。

    TInterfacedObject 已经为您实现了这些方法。
    实现IInterface (aka IUnknown) 的其他基础对象是:TAggregatedObjectTContainedObject。然而,这些都是特殊用途的工具,只有在您真正知道自己在做什么时才能使用。

    将类的定义更改为

    TTPA_MailJournal = class(TInterfacedObject, ITable)
    

    您的代码将被编译。

    请参阅Delphi basics 了解更多信息。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    相关资源
    最近更新 更多