1

我有一个接口和一个相应的对象。例如...

  IMyInterface = interface
    function GetSomething: WideString;
    procedure SetSomething(const Value: WideString);
    property Something: WideString read GetSomething write SetSomething
  end;

  TMyObject = class(TInterfacedObject, IMyInterface)
  private
    function GetSomething: WideString;
    procedure SetSomething(const Value: WideString);
  public
    property Something: WideString read GetSomething write SetSomething
  end;

我使用此接口能够跨 DLL 与此对象进行交互。

现在我想继承这个对象并覆盖其中一些方法......

  TMyOtherObject = class(TMyObject)
  private
    function GetSomething: WideString; override;
    procedure SetSomething(const Value: WideString); override;

除了我想让基本字段虚拟化和抽象化以基本上强制孩子继承这些......

  TMyObject = class(TInterfacedObject, IMyInterface)
  private
    function GetSomething: WideString; virtual; abstract;
    procedure SetSomething(const Value: WideString); virtual; abstract;

我可以这样做并让界面仍然适用于这些字段吗?我是否也需要在界面中以这种方式定义它?(我当然知道接口中的所有字段都是抽象的)

4

1 回答 1

4

你确实可以做到这一点。可以使用抽象或其他方式的虚拟方法来满足接口契约。

您不能将接口方法声明为virtualor abstract。无论如何,这没有什么意义,因为virtualandabstract是实现的属性而不是接口。

最后,您不需要在实现对象中再次声明该属性。由于我希望您只会通过接口引用这些对象,因此重复属性声明毫无意义。

这是一个简单的程序来证明这一点:

{$APPTYPE CONSOLE}

type
  IMyInterface = interface
    procedure Foo;
  end;

  TMyObject = class(TInterfacedObject, IMyInterface)
  private
    procedure Foo; virtual; abstract;
  end;

  TMyOtherObject = class(TMyObject)
  private
    procedure Foo; override;
  end;

procedure TMyOtherObject.Foo;
begin
  Writeln(ClassName);
end;

var
  Intf: IMyInterface;

begin
  Intf := TMyOtherObject.Create;
  Intf.Foo;
  Readln;
end.
于 2013-09-03T11:16:08.960 回答