【问题标题】:Interfaces polymorphism in DelphiDelphi中的接口多态性
【发布时间】:2013-05-17 04:26:07
【问题描述】:

我有两个接口,一个来自另一个接口:

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

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

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

procedure DoSomething(SomeInterface: ISomeInterface);

我想检查 SomeInterface 是否为 ISomeInterfaceChild。 Delphi 7 的接口不支持Is 运算符,我也不能在这里使用Supports。我能做什么?

【问题讨论】:

    标签: delphi oop interface delphi-7


    【解决方案1】:

    您确实可以使用Supports。您只需要:

    Supports(SomeInterface, ISomeInterfaceChild)
    

    这个程序说明:

    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.
    

    输出

    错误的 真的

    【讨论】:

      【解决方案2】:

      为什么说不能使用Supports 函数?这似乎是解决方案,它有一个重载版本,它将IInterface 作为第一个参数所以

      procedure DoSomething(SomeInterface: ISomeInterface);
      var tmp: ISomeInterfaceChild;
      begin
        if(Supports(SomeInterface, ISomeInterfaceChild, tmp))then begin
           // argument is ISomeInterfaceChild
        end;
      

      应该做你想做的。

      【讨论】:

      • 如果只需要检查接口是否支持ISomeInterfaceChild,那么您使用了错误的重载。您应该使用我在回答中演示的两个参数重载。
      • 好吧,我假设如果您需要检查参数ISomeInterfaceChild,您还需要使用ISomeInterfaceChild。否则检查不太有意义,它应该无关紧要,因此检查它可能表明存在设计问题。
      • @ain:不一定。有时,接口用于宣传包含对象的特征,而实际上并未为它们公开新功能。在这种情况下,只需检查是否存在受支持的接口就足够了。
      猜你喜欢
      • 2016-09-12
      • 2011-02-20
      • 2011-09-24
      • 1970-01-01
      • 2017-11-28
      • 2020-12-27
      • 2017-10-22
      • 2011-04-27
      • 1970-01-01
      相关资源
      最近更新 更多