Delphi中的接口多态性

Jus*_*tMe 3 delphi oop interface delphi-7

我有两个接口来自antoher:

type
  ISomeInterface = interface
    ['{5A46CC3C-353A-495A-BA89-48646C4E5A75}']
  end;

  ISomeInterfaceChild = interface(ISomeInterface)
    ['{F64B7E32-B182-4C70-A5B5-72BAA92AAADE}']
  end;
Run Code Online (Sandbox Code Playgroud)

现在我有一个参数是ISomeInterface的过程,如:

procedure DoSomething(SomeInterface: ISomeInterface);
Run Code Online (Sandbox Code Playgroud)

我想检查SomeInterface是否是ISomeInterfaceChild.IsDelphi 7中的接口不支持operator,我也不能Supports在这里使用.我能做什么?

Dav*_*nan 5

你确实可以使用Supports.所有你需要的是:

Supports(SomeInterface, ISomeInterfaceChild)
Run Code Online (Sandbox Code Playgroud)

该计划说明:

program SupportsDemo;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  ISomeInterface = interface
    ['{5A46CC3C-353A-495A-BA89-48646C4E5A75}']
  end;

  ISomeInterfaceChild = interface(ISomeInterface)
    ['{F64B7E32-B182-4C70-A5B5-72BAA92AAADE}']
  end;

procedure Test(Intf: ISomeInterface);
begin
  Writeln(BoolToStr(Supports(Intf, ISomeInterfaceChild), True));
end;

type
  TSomeInterfaceImpl = class(TInterfacedObject, ISomeInterface);
  TSomeInterfaceChildImpl = class(TInterfacedObject, ISomeInterface, ISomeInterfaceChild);

begin
  Test(TSomeInterfaceImpl.Create);
  Test(TSomeInterfaceChildImpl.Create);
  Readln;
end.
Run Code Online (Sandbox Code Playgroud)

产量

False
True